Data Annotation Attribute On Code First Approach

  1. Key: This is user to make the primary key on the Data Table
  2. TimeStamp
  3. ConcurrencyCheck: In Case of Update command In Entity Framework takes value of this column in the Where Clause.
  4. Required: Entity Framework Create a Not null Property in the database.
  5. Max/min Length: It can be applied only string or array type of property in Model Class.
  6. StringLength: Code first create a fix size of column in the string length. Here is very interesting point that then whats the use of max length. According to me the maxlength is used to create the column in DB while Stringlength is used for client side validation.
  7. Table: Attibute is used to create the Table with the specified name.
  8. Column: Create a column with that name (default is model property name). You can also specify an order and type of the column using Column attribute.
  9. ForeignKey: By default the Foreignkey is set by the reference property.
    1. //Foreign key for Standard
    2. public int StandardId
    3. {
    4. get;
    5. set;
    6. }
    7. public Standard Standard
    8. {
    9. get;
    10. set;
    11. }
    12. public int StandardId
    13. {
    14. get;
    15. set;
    16. }
    17. public string StandardName
    18. {
    19. get;
    20. set;
    21. }
    22. // But the Foreign key DataAnnotation can change the default behaviour
    23. public class Student
    24. {
    25. public Student()
    26. {
    27. }
    28. public int StudentID
    29. {
    30. get;
    31. set;
    32. }
    33. public string StudentName
    34. {
    35. get;
    36. set;
    37. }
    38. //Foreign key for Standard
    39. public int StandardRefId
    40. {
    41. get;
    42. set;
    43. }
    44. [ForeignKey("StandardRefId")]
    45. public Standard Standard
    46. {
    47. get;
    48. set;
    49. }
    50. }
    51. public class Standard
    52. {
    53. public Standard()
    54. {
    55. }
    56. public int StandardId
    57. {
    58. get;
    59. set;
    60. }
    61. public string StandardName
    62. {
    63. get;
    64. set;
    65. }
    66. public ICollection < Student > Students
    67. {
    68. get;
    69. set;
    70. }
    71. }
  10. NotMapped: Implementing this column the Default Column is not created. Code first also does not create a column for a properties which does not have either getters or setters as:
    1. public string FirstName { get{ return StudentName;} }
    2. public string Age { set{ _age = value;} }
  11. InverseProperty: Code First creates {Class Name}_{Primary Key} foreign key column if you have not included foreign key property in a parent class. The InverseProperty attribute is used when you have multiple relationships between classes.

    Fluent API is another way to configure your domain classes. Fluent API provides more functionalities for configuration than DataAnnotations. Fluent API supports following types of mappings.