Published on February 26, 2014 in Entity Framework · Read time 1 minutes · 0 Comments

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

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

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.

OctocatWant to make a change?
Edit this page on GitHub

Jon Preece

Written by Jon Preece who lives and works in Manchester, North West England. You should follow him on Twitter.


Discussion