Introduction
Entity Framework provides two ways to add configuration to model classes.
- DataAnnotation Attribute - Data Annotation Attributes can only add the some property of the table.
Namespace ( System.ComponentModel.DataAnnotations)
- DataAnnotation Schema Attribute - Data Annotation Schemas are used to change or modify the structure of table.
Namespace (System.ComponentModel.DataAnnotations.Schema)
Data Annotation Attributes
- Key: Key is mainly used to define the primary or composite key on table.
- ConcurrencyCheck: ConcurrencyCheck annotation allows you to flag one or more properties to be used for concurrency checking in the database when a user edits or deletes an entity.
- StringLength: StringLength is user to define the length of string allowed in table
- MinLength: MinLength define the minimum required length of string.
- MaxLength: MaxLength define the minimum required length of string.
- Required: The Required annotation will ensure that property has data in it.
Data Annotation Schema Attributes:
- Table: Provides the alternate table name.
- Column: Used to provide the column name or column schema.
- Foreign Key: Create a relationship
- Index: To defined the clustered/non clustered index.
- Complex Type: Make the class ascComplex type.
Example:
Here is the example code of how these attributes can be used.
Employee Class:
- using System.ComponentModel.DataAnnotations;
- using System.ComponentModel.DataAnnotations.Schema;
- namespace EntityFrameworkCodeFirst
- {
- [Table("tblEmp")]
- public class Employee
- {
-
- [Key]
- public int ID
- {
- get;
- set;
- }
- [Required]
- public string Title
- {
- get;
- set;
- }
- [StringLength(25)]
- public string EmployeeName
- {
- get;
- set;
- }
- [MinLength(5)]
- public decimal Salary
- {
- get;
- set;
- }
-
- [ForeignKey("DepartmentID")]
- public int DepartmentID
- {
- get;
- set;
- }
- }
- }
Department Class
- public class Department
- {
- public int DepartmentID
- {
- get;
- set;
- }
- public string DepartmentName
- {
- get;
- set;
- }
- public List < Employee > Employees
- {
- get;
- set;
- }
- }