--- layout: post title: Column Attribute in Entity Framework 5 date: 2012-10-06 11:14:29.000000000 -04:00

When developing applications using Entity Framework code first approach, you may use Column data annotation on your model properties to define what attributes that property has, ex : name, type etc.

in Entity Framework 4.3.1,  ColumnAttribute is defined in System.ComponentModel.DataAnnotations namespace which is available in EntityFramework.dll. So you need to add a reference to EntityFramework.dll and include a using statement in your class to use that.

using System.ComponentModel.DataAnnotations;
namespace YourProject.Models
{
    public class User
    {
        public int CustomerID { set; get; }

        [Column(TypeName = "ntext")]
        public string AboutText { get; set; }
    }
}

 

But in EntityFramework 5, If you use the same code, you will get a compile time error like below

The type or namespace name 'ColumnAttribute' could not be found (are you missing a using directive or an assembly reference?)

The reason for this error is, in  Entity Framework 5, they moved the ColumnAttribute class to a different namespace called System.ComponentModel.DataAnnotations.Schema. So you need to add a using statement to include that namespace too in your model class.

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace YourProject.Models
{
    public class User
    {
        public int CustomerID { set; get; }

        [Column(TypeName = "ntext")]
        public string AboutText { get; set; }
    }
}

People usually get this error, when they follow a book which has sample code which uses Entity Framework 4.3.1 and they try to create the project and download Entity Framework via nuget where they will get the latest version, Entity framework 5 ( at the time of this post). Adding the relevant namespace will fix the issue.

More info in msdn,

ColumnAttribute class

System.ComponentModel.DataAnnotations.Schema Namespace

If interested, you can see the source code by checking the class in any assembly decompiling tools.

ColumnAttribute in EntityFramework 5