Data Annotations Column Attribute in EF 6 & EF Core

The Entity Framework Code first conventions or EF Core Conventions names the database column name after the property names. You can override this behavior using the Column Attribute.

Column Convention

Consider the following model. The Default convention is that the database fields are named after the property name. The Data type of the fields is determined by the property data type and the order of the fields in tables follows the order in which properties defined in the model.

Column Convention in Entity Framework

Entity Data Types to SQL data type mapping in Data Type Mapping in EF Core & in Data Type Mapping in EF

Column Attribute

By Applying the Column attribute, we can change the column name, datatype, and order of the column. The attribute takes the following argument

Where
Name: Name of the database column
Order: Sets the zero-based Order of the field in the table
TypeName: Database Provider-specific data type of the column the property

Best Entity Framework Core Books

Best Entity Framework Books

Column Name

Column attributes used to specify the column names. EF by convention creates the columns using the property name. If the Column attribute is present, then the EF will use the attribute value as the column name when creating the table

Data Annotations Column Attribute

Data type 

Use the TypeName option to set the data type of the column. In the following example, EmployeeName is set as the varchar data type. Name1 is set as the nvarchar data type. TextColumn as the ntext data type and amount as money data type

Data Annotations Column Attribute Type Name
Data Annotations Column Attribute Type Name

TypeName attribute is different from the DataType data annotation attribute, which is used only for the UI Validations

Column Order

Specify the order of the column using the Order option. The Order can be any integer value. The EF will create the column based on the Order specified. The Unordered column appears after the ordered column as shown in the image below

Data Annotations Column Attribute Column Order

References

  1. Column Attribute
  2. Entity Framework Conventions
  3. Entity Framework Core Conventions
  4. DataType Attribute

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top