Data Annotations Column Attribute in Entity Framework

The Entity Framework Code first conventions name 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 names the database fields after the property name. The property data type determines the column type of the database field. The order of the fields in the table follows the order in which we define properties in the model.

Column Convention in Entity Framework

The following table shows how data types are mapped to the database columns.

Data TypeMapped to
stringnvarchar(max)
decimaldecimal(18, 2), not null
decimal?decimal(18, 2), null
doublefloat, not null
double?float, null
intint, not null
int?int, null
boolbit, not null
bool?bit, null
DateTimedatetime, not null
DateTime ?datetime, null
byte[]varbinary(max)

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

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 in Entity Framework

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

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

The Entity Framework does not allow us to set the field length in TypeName attribute

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 with column order

References

  1. Column Attribute
  2. DataType Attribute

4 thoughts on “Data Annotations Column Attribute in Entity Framework”

Leave a Comment

Your email address will not be published. Required fields are marked *

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

Scroll to Top