代码改变世界

Entity Framework Code-First(9):DataAnnotations

2016-07-05 16:23  追忆似水流年  阅读(257)  评论(0编辑  收藏  举报

DataAnnotations in Code-First:

EF Code-First provides a set of DataAnnotation attributes, which you can apply to your domain classes and properties. DataAnnotation attributes override default Code-First conventions.System.ComponentModel.DataAnnotations includes attributes that impacts on nullability or size of the column. System.ComponentModel.DataAnnotations.Schema namespace includes attributes that impacts the schema of the database.

Note: DataAnnotations only give you a subset of configuration options. Fluent API provides a full set of configuration options available in Code-First.

System.ComponentModel.DataAnnotations Attributes:

AttributeDescription
Key Mark property as EntityKey which will be mapped to PK of the related table.
Timestamp Mark the property as a non-nullable timestamp column in the database.
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.
Required The Required annotation will force EF (and MVC) to ensure that property has data in it.
MinLength MinLength annotation validates property whether it has minimum length of array or string.
MaxLength MaxLength annotation is the maximum length of property which in turn sets the maximum length of a column in the database
StringLength Specifies the minimum and maximum length of characters that are allowed in a data field.

System.ComponentModel.DataAnnotations.Schema Attributes:

AttributeDescription
Table Specify name of the DB table which will be mapped with the class
Column Specify column name and datatype which will be mapped with the property
Index Create an Index for specified column. (EF 6.1 onwards only)
ForeignKey Specify Foreign key property for Navigation property
NotMapped Specify that property will not be mapped with database
DatabaseGenerated DatabaseGenerated attribute specifies that property will be mapped to computed column of the database table. So, the property will be read-only property. It can also be used to map the property to identity column (auto incremental column).
InverseProperty InverseProperty is useful when you have multiple relationships between two classes.
ComplexType Mark the class as complex type in EF.

Learn about each DataAnnotation attributes in the next sections.