Jon Preece

Follow DeveloperHandbook.com on TwitterJon Preece
Feb 26, 2014 ยท 1 minute read

At the time of writing, beta 1 of Entity Framework 6.1 has recently been released. This is mostly a maintenance release, however, there are several new feature of note, including the ability to add indexes using a new data annotation when developing using the code first approach.

Add indexes using the Index attribute

To add an index, simply add the Index attribute as required;

public class Customer {
 [Index] public int Id {
  get;
  set;
 }
}

A quick look in SQL Server Management studio reveals that the index has been added for us.

image
image

The key created was non-unique, non-clustered. There are overloads available to override these defaults;

[Index(isClustered = false, isUnique = true)]
public int Id {
 get;
 set;
}

Which results in a unique index as shown below;

indexes
indexes

Summary

This is a fantastic new feature for potentially improving the performance of your code first applications by reducing the time required to query data. You can add indexes to your database using the Index attribute, and override the default Unique and Clustered settings to get the index best suited to your scenario.

Entity FrameworkC#.NET

Jon Preece

About the author

I am Jon Preece, an experienced website and software developer from the United Kingdom, based in Manchester.

Throughout my 10+ year professional career I have worked in many sectors, including; e-commerce, financial services, marketing, healthcare, travel and accountancy. Get in touch via Twitter.