Entity Framework Code First Data Annotations by Examples

Two commonly used namespaces for Entity Framework Code First data annotation are:


One of common use of Table data annotation schema is to specify created table name in database. Without Table data annotation, Entity Framework Code First will create a table using the class name with an ‘s’ character at the end. For below example model class without specifying Table data annotation, an Employees table will be created.


Key data annotation is used to specify a property as primary key field of a table in database. By convension, Entity Framework Code First will try to identify a property that it can use as primary key field based on model class property name, for example if it sees first property variable name such Id or EmployeeId property name, it will use this property name as column name and set it as primary key.


The Required data annotation specify that the field is a required field and EF Code First will set the field as a non-nullable field, i.e. NOT NULL field.


StringLength attribute is used to specify the maximum number of allowed characters for the field. EF Code First will also specify field size, i.e. nvarchar(100) instead of nvarchar(MAX).


Index attribute is used to specify the property to be an indexed field in a table. Also, StringLength attribute is required for indexed field of type string.


NotMapped attribute is used to specify that the property will be ignored or not mapped to database. NotMapped field will not be created during table creation.