John John - 1 year ago 165
C# Question

Creating Unique Index with Entity Framework 6.1 fluent API

I have a column "Name" that must be unqiue. No foreign key or anything like that.

EF 6.1 finally supports creating such indexes via Annotations. That has been discussed already on SO. But it seems it can only be done via annotations in the classes. How do I do that using only the Fluent API?

Something like this:

public class PersonConfiguration : EntityTypeConfiguration<Person>
public PersonConfiguration()
HasKey( p => p.Id );
Property( p => p.Id ).HasDatabaseGeneratedOption( DatabaseGeneratedOption.Identity );

//not possible?
Index( p => p.Name ).IsUnique(); //???

Thank you.

Answer Source

You can use IndexAttribute as mentioned but with Fluent API instead of DataAnnotations which will do the trick:

    .Property(t => t.Name) 
        new IndexAnnotation(new IndexAttribute("IX_Name") { IsUnique = true }));

Unfortunately there is no other way to create unique indexes using Fluent API. There is an open issue regarding this feature: Unique Constraints (Unique Indexes)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download