Data Annotation Column Attribute in EF Core

The Entity Framework core 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 Data type of property determines the data type of the field. The order of the fields in tables follows the order in which properties defined in the model.

Column name convention in Ef Core

The following table shows data type to column type mapping. Since Name is a string is it mapped to nvarchar(max).

Data typeMappedNull ?
stringnvarchar(max)Null
decimaldecimal(18, 2)Not Null
decimal?decimal(18, 2)Null
doublefloatNot Null
double?floatNull
intintNot Null
int?intNull
boolbitNot Null
bool?bitNull
DateTimedatetimeNot Null
DateTime?datetimeNull
byte[]varbinary(max)Null
bytetinyintNot Null
byte?tinyintNull
uintbiintnot null
uint?biint ?null
shortsmallintnot null
ushortintnot null
charnvarchar(1)not null

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

Column Attribute in EF Core

Note that CustomerName has field length set as nvarchar(max)

Data type 

Use the TypeName option to set the data type of the column. In the following example, EmployeeName is set as the varchar(100) datatype. Name1 is set as the nvarchar(100) datatype etc.

Column Attribute in EF Core

TypeName attribute is different from the DataType data annotation attribute, which is used only for the UI Validations. Note that TypeName = "varchar" converts to varchar(1) column

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.

EF Core does not currently support the Column Order. You can follow the issue from here

References

  1. Column Attribute
  2. DataType Attribute

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