Create an Index for you Entity Framework Index
Posted on: 2015-03-27
Either you are working with a field that require a fast access or if the field is used as reference in some case, you will need to create an Index. Unfortunately, Entity Framework does not offer a quick way to do it. To tell Entity Framework to generate the Sql Index on the column, you must use a Column Annotation. Entity Framework column annotation has an already created class named IndexAnnotation that can be added to your column.
this.Property(d => d.Date) .HasColumnAnnotation("Index" , new IndexAnnotation( new IndexAttribute("IX_Date") {IsUnique = true} ) );
The code above set for a Date column an index. It creates a IndexAnnotation which create a unique index attribute.
This result into an Index inside the migration class with a unique property set to true.
CreateTable( "YourEntityName", c => new { Id = c.Int(nullable: false, identity: true), Date = c.DateTime(nullable: false), }) .PrimaryKey(t => t.Id) .Index(t => t.Date, unique: true);