Back to: Entity Framework Tutorials For Begineers and Professionals
Column Data Annotation Attribute in Entity Framework
In this article, I am going to discuss Column Data Annotation Attribute in Entity Framework Code First Approach with Examples. Please read our previous article where we discussed Table Data Annotation Attribute in Entity Framework Code First Approach with Examples.
Column Data Annotation Attribute in Entity Framework Code First
The Column Data Annotation Attribute can be applied to one or more properties of a domain entity to configure the corresponding database column name, column order, and column data type. That means it represents the database column that a property is mapped to.
The Column Data Annotation Attribute in Entity Framework overrides the default convention. As per the default conventions in Entity Framework, it creates the database table column with the same name and the same order as the property names in the model class. Now, if you go to the definition of Column Attribute, then you will see the following.
As you can see in the above image, this class has two constructors. The 0-Argument constructor will create the database column with the same name as the property name while the other overloaded constructor which takes the string name as a parameter will create the database table column with the passed name. Again, this Column attribute has three properties. The meaning of the properties are as follows:
- Name: Gets the name of the column the property is mapped to. This is a read-only property.
- Order: Gets or sets the zero-based order of the column the property is mapped to. It returns the order of the column. This is a read-write property.
- TypeName: Gets or sets the database provider-specific data type of the column the property is mapped to. It returns the database provider-specific data type of the column the property is mapped to. This is a read-write property.
Syntax to use Column Attribute: [Column (string name, Properties: [Order = int], [TypeName = string])]
Example to use Column Attribute: [Column(“DOB”, Order = 2, TypeName = “DateTime2”)]
Examples to understand Column Data Annotation Attribute in Entity Framework:
Let us understand Column Data Annotation Attribute in Entity Framework Code First Approach with an example. Let us modify the Student Entity class as follows. As you can see, we have specified the Column Attribute with the FirstName and LastName properties. With the FirstName property, we have not provided the string name i.e. using the 0-Argument constructor, so in this case, it will create the database table column with the same name as the Property name. With the LastName property, we have specified the name as LName i.e. using the constructor which takes one string parameter, so in this case, it will create the database table column with the name LName which is mapped to the LastName property. The Column attribute belongs to System.ComponentModel.DataAnnotations.Schema namespace.
using System.ComponentModel.DataAnnotations.Schema; namespace EFCodeFirstDemo { public class Student { public int StudentId { get; set; } [Column] public string FirstName { get; set; } [Column("LName")] public string LastName { get; set; } } }
As we are going to update the Entity Models many times, in order to avoid the RunTime Exception when the model changes and when we rerun the application, let us set the database initializer as DropCreateDatabaseIfModelChanges. So, modify the context class as follows:
using System.Data.Entity; namespace EFCodeFirstDemo { public class EFCodeFirstContext : DbContext { public EFCodeFirstContext() : base("name=MyConnectionString") { //Setting the Database Initializer as DropCreateDatabaseIfModelChanges Database.SetInitializer(new DropCreateDatabaseIfModelChanges<EFCodeFirstContext>()); } protected override void OnModelCreating(DbModelBuilder modelBuilder) { } public DbSet<Student> Students { get; set; } } }
Please make sure to have the connection string with the name MyConnectionString within the app.config file or web.config file as shown in the below image.
Now, modify the Main method of the Program class as follows. Here, we are adding one student entity to the database.
using System; namespace EFCodeFirstDemo { class Program { static void Main(string[] args) { using (EFCodeFirstContext context = new EFCodeFirstContext()) { var student = new Student() { FirstName = "Pranaya", LastName="Rout" }; context.Students.Add(student); context.SaveChanges(); Console.WriteLine("Student Added"); Console.ReadKey(); } } } }
With the above changes in place, run the application and verify the database and you should see the following. As you can see, the FirstName is created as FirstName, but the LastName property is created as the LName column in the database as expected.
Column Data Type in Entity Framework:
As we see, the Column Attribute class is having a property called TypeName, and that TypeName property is used to get or set the data type of a database column. That means this property gets or sets the database provider-specific data type of the column the property is mapped to. For a better understanding, please modify the Student Entity as follows. Here, you can see, we have set the DateOfBirth column name as DOB and Data type as DateTime2 using TypeName Property.
using System; using System.ComponentModel.DataAnnotations.Schema; namespace EFCodeFirstDemo { public class Student { public int StudentId { get; set; } [Column] public string FirstName { get; set; } [Column("LName")] public string LastName { get; set; } [Column("DOB", TypeName = "DateTime2")] public DateTime DateOfBirth { get; set; } } }
With the above changes in place, now run the application code. It should create a column with the name as DOB with the data type as DateTime2 instead of DateTime. You can verify the same in the database as shown in the below image.
Column Order in Entity Framework Code First Approach:
Another property called Order is provided by the Column Attribute class which is used to set or get the order of the columns. It is 0 Based orders i.e. it is going to start from 0. As per the default convention, the Primary Key columns will come first, and then the rest of the columns based on the order that we specified in the Column Attribute Order Property. The most important point that you need to remember is the Order Property of the Column Attribute must be applied to all the properties of an Entity with a different index, starting from zero. For a better understanding, please have a look at the following example.
using System; using System.ComponentModel.DataAnnotations.Schema; namespace EFCodeFirstDemo { public class Student { //Primary Key: Order Must be 0 [Column(Order = 0)] public int StudentId { get; set; } [Column(Order = 2)] public string FirstName { get; set; } [Column("LName", Order =4)] public string LastName { get; set; } [Column("DOB", Order =3, TypeName = "DateTime2")] public DateTime DateOfBirth { get; set; } [Column(Order = 1)] public string Mobile { get; set; } } }
Now, run the application and verify the database table columns order and it should be in proper order as per the Order parameter as shown in the below image.
How to fetch the Column Attribute details in Entity Framework?
If you remember, the Column Attribute class has three properties i.e. Name, Order, and TypeName and all these three properties are having the get accessors. Let us understand how to use these get accessors to fetch the column details. Fetch all the column attributes details like Name, Order, and Data Type. To do so, modify the Main Method of the Program class as follows:
using System.ComponentModel.DataAnnotations.Schema; using System.Reflection; using System; namespace EFCodeFirstDemo { class Program { static void Main(string[] args) { using (EFCodeFirstContext context = new EFCodeFirstContext()) { //Fetch Attribute Details GetAttribute(typeof(Student)); Console.ReadKey(); } } public static void GetAttribute(Type t) { PropertyInfo[] propertiesInfo = t.GetProperties(); foreach (PropertyInfo propertyInfo in propertiesInfo) { // Get instance of the attribute. ColumnAttribute columnAttribute = (ColumnAttribute)Attribute.GetCustomAttribute(propertyInfo, typeof(ColumnAttribute)); if (columnAttribute == null) { Console.WriteLine("The Attribute was not found."); } else { // Get the Name, Order and DataType values. Console.WriteLine($"Name: {columnAttribute.Name}, Order: {columnAttribute.Order}, Data Type: {columnAttribute.TypeName}"); } } } } }
When you run the above code, whatever Name, Order and Data type you have specified those are going to be printed on the Console window as shown in the below image.
Now, let us fetch single-column information. We have set the Name, Order. and data Type of the DateOfBirth property. Let us fetch that property-related database column information. To do so, modify the Main Method of the Program class as follows:
using System.ComponentModel.DataAnnotations.Schema; using System.Reflection; using System; namespace EFCodeFirstDemo { class Program { static void Main(string[] args) { using (EFCodeFirstContext context = new EFCodeFirstContext()) { //Fetch Attribute Details GetAttribute(typeof(Student)); Console.ReadKey(); } } public static void GetAttribute(Type t) { //Fetch the DateOfBirth Property details PropertyInfo propertyInfo = t.GetProperty("DateOfBirth"); // Get instance of the attribute. ColumnAttribute columnAttribute = (ColumnAttribute)Attribute.GetCustomAttribute(propertyInfo, typeof(ColumnAttribute)); if (columnAttribute == null) { Console.WriteLine("The DateOfBirth Column Property was not found."); } else { // Get the Name value. Console.WriteLine($"Name of Column is: {columnAttribute.Name}"); // Get the Order value. Console.WriteLine($"Order of Column is: {columnAttribute.Order}"); // Get the DataType value. Console.WriteLine($"Data Type of Column is: {columnAttribute.TypeName}"); } } } }
Output:
In the next article, I am going to discuss Key Attributes in Entity Framework Code First Approach with Examples. Here, in this article, I try to explain Column Data Annotation Attribute in Entity Framework Code First Approach with Examples. I hope you enjoyed this Column Data Annotation Attribute in Entity Framework Code First Approach with Examples article. Please give your valuable feedback and suggestions about this article.