Introduction

Entity Framework provides two ways to add configuration to model classes.

Data Annotation Attributes

Data Annotation Schema Attributes:

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. }