The Column attribute can be applied to one or more properties in an entity class to configure the corresponding column name, data type and order in a database table. The Column attribute overrides the default convention. As per the default conventions in EF 6 and EF Core, it creates a column in a db table with the same name and order as the property names.
Column Attribute: [Column (string name, Properties:[Order = int],[TypeName = string])
The following example changes the name of a column.
using System.ComponentModel.DataAnnotations.Schema; public class Student { public int StudentID { get; set; } [Column("Name")] public string StudentName { get; set; } public DateTime? DateOfBirth { get; set; } public byte[] Photo { get; set; } public decimal Height { get; set; } public float Weight { get; set; } }
In the above example, the Column attribute is applied to a StudentName
property. So, EF will override the default conventions and create a Name
column instead of the StudentName
column in the Students
table as shown below.
Use the TypeName
parameter in the column attribute to change the appropriate data type of the corresponding db column, as shown below.
using System.ComponentModel.DataAnnotations.Schema; public class Student { public int StudentID { get; set; } [Column("Name")] public string StudentName { get; set; } [Column("DoB", TypeName="DateTime2")] public DateTime DateOfBirth { get; set; } public byte[] Photo { get; set; } public decimal Height { get; set; } public float Weight { get; set; } }
In the above example, TypeName = "DateTime2"
parameter is applied on the DateOfBirth
property. This will create a DateTime2
type column instead of DateTime
as shown below.
Use the zero-based Order
parameter to set the order of columns in the database. As per the default convention, PK columns will come first and then the rest of the columns based on the order of their corresponding properties in an entity class.
Note: The Order parameter must be applied on all the properties with a different index, starting from zero.
using System.ComponentModel.DataAnnotations.Schema; public class Student { [Column(Order = 0)] public int StudentID { get; set; } [Column("Name", Order = 1)] public string StudentName { get; set; } [Column("DoB", Order = 5)] public DateTime DateOfBirth { get; set; } [Column(Order = 3)] public byte[] Photo { get; set; } [Column(Order = 2)] public decimal Height { get; set; } [Column(Order = 4)] public float Weight { get; set; } }
The above example will create the columns in the specified order as shown below.