In this tutorial, we will give you a short introduction to the data annotations in Entity Framework Code First. The Data annotations attribute classes are used to decorate the classes or properties. These attributes help Entity Framework Code First to apply pre-defined rules on entity models
We have seen how to use code first conventions in our previous tutorial. We can further fine tune our model using the Data Annotation attribute. The Data Annotation attributes override the default Code First conventions.
The Data annotation attributes are grouped into two categories
- Data modeling attributes
- Validation Attributes
Table of Contents
- 1 Data modeling attributes
- 2 Validation related Attributes
- 3 Conclusion
Data modeling attributes
The Data modeling attributes specify the schema of the database. These attributes are present in the namespace System.ComponentModel.DataAnnotations.Schema.
The following attributes are present in the above namespace
You can specify the name of the table to which the entity class maps to using these attributes
Allows us to specify the name of the column.
This attribute specifies that the class is a complex type.
This attribute added on the properties whose value is automatically updated by the Database.
Foreign Key Attribute is applied to a property, which participates as a foreign key in a relationship
Inverse Property is used when you have many to many relationships between entities. Specified on the property which is at the other end of the relationship.
NotMapped attribute is applied on those properties, which you do not want to include in your database table.
The Validation related attributes reside in the System.ComponentModel.DataAnnotations namespace. These attributes are used to enforce validation rules for the entity properties.
This attribute is applied to a property, which participates in concurrency check validation while updating or deleting an entity
This attribute is applied to the property or properties, that are part of the primary key.
This validation attribute specifies the max length of the column in the database.
This validation attribute specifies the minimum length of the data allowed in a string or array property.
Specifies that a data field value is required. Specify the column as nonnullable.
Specifies the minimum and maximum length of characters that are allowed in a data field. This attribute is similar to MaxLength & MinLength attribute
Specifies the data type of the column as a row version.
Entity Framework Code First model allows us various ways to configure the model class. Default Code First Convention, using data annotation attributes or by using fluent API. In this tutorial, we looked at Data annotation attributes. In the next few tutorials, we will look at each of the above data annotations in entity framework attributes and how to use them with examples.