Data Annotation Attribute On Code First Approach
- Key: This is user to make the primary key on the Data Table
- TimeStamp
- ConcurrencyCheck: In Case of Update command In Entity Framework takes value of this column in the Where Clause.
- Required: Entity Framework Create a Not null Property in the database.
- Max/min Length: It can be applied only string or array type of property in Model Class.
- 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.
- Table: Attibute is used to create the Table with the specified name.
- 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.
- ForeignKey: By default the Foreignkey is set by the reference property.
-
- public int StandardId
- {
- get;
- set;
- }
-
- public Standard Standard
- {
- get;
- set;
- }
- public int StandardId
- {
- get;
- set;
- }
- public string StandardName
- {
- get;
- set;
- }
-
- public class Student
- {
- public Student()
- {
-
- }
- public int StudentID
- {
- get;
- set;
- }
- public string StudentName
- {
- get;
- set;
- }
-
- public int StandardRefId
- {
- get;
- set;
- }
- [ForeignKey("StandardRefId")]
- public Standard Standard
- {
- get;
- set;
- }
- }
- public class Standard
- {
- public Standard()
- {
-
- }
- public int StandardId
- {
- get;
- set;
- }
- public string StandardName
- {
- get;
- set;
- }
- public ICollection < Student > Students
- {
- get;
- set;
- }
- }
- 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:
- public string FirstName { get{ return StudentName;} }
- public string Age { set{ _age = value;} }
- 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.