Home » Ado.Net » Entity Framework » Create an Index for you Entity Framework Index

Create an Index for you Entity Framework Index

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);

If you like my article, think to buy my annual book, professionally edited by a proofreader. directly from me or on Amazon. I also wrote a TypeScript book called Holistic TypeScript

One Response so far.

  1. ErikEJ says:

    You can use this today: https://github.com/mj1856/EntityFramework.IndexingExtensions and a PR for fluent API in the works

Leave a Reply

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.