Data Annotations in Entity Framework Code First

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:

  1. using System.ComponentModel.DataAnnotations;  
  2. using System.ComponentModel.DataAnnotations.Schema;  
  3. namespace EntityFrameworkCodeFirst  
  4. {  
  5.     [Table("tblEmp")]  
  6.     public class Employee  
  7.     {  
  8.         //Defined Primary Key  
  9.         [Key]  
  10.         public int ID  
  11.         {  
  12.             get;  
  13.             set;  
  14.         }  
  15.         [Required]  
  16.         public string Title  
  17.         {  
  18.             get;  
  19.             set;  
  20.         }  
  21.         [StringLength(25)]  
  22.         public string EmployeeName  
  23.         {  
  24.             get;  
  25.             set;  
  26.         }  
  27.         [MinLength(5)]  
  28.         public decimal Salary  
  29.         {  
  30.             get;  
  31.             set;  
  32.         }  
  33.         //Foreign key for Department  
  34.         [ForeignKey("DepartmentID")]  
  35.         public int DepartmentID  
  36.         {  
  37.             get;  
  38.             set;  
  39.         }  
  40.     }  
  41. }  
Department Class
  1. public class Department  
  2. {  
  3.     public int DepartmentID  
  4.     {  
  5.         get;  
  6.         set;  
  7.     }  
  8.     public string DepartmentName  
  9.     {  
  10.         get;  
  11.         set;  
  12.     }  
  13.     public List < Employee > Employees  
  14.     {  
  15.         get;  
  16.         set;  
  17.     }  
  18. }