Unique keys in Entity Framework 4

The Entity Framework 6.1 now supports uniques with both Data Annotations and Fluent API.

Data Annotations (Reference)

public class MyEntityClass
{ 
    [Index(IsUnique = true)]
    [MaxLength(255)] // for code-first implementations
    public string MyUniqueProperty{ get; set; } 
}

Fluent API (Reference)

public class MyContext : DbContext
    {
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder 
                .Entity<MyEntityClass>() 
                .Property(t => t.MyUniqueProperty) 
                .HasMaxLength(255) // for code-first implementations
                .HasColumnAnnotation( 
                    "Index",  
                    new IndexAnnotation(new[] 
                        { 
                            new IndexAttribute("Index") { IsUnique = true } 
                        })));
        }
    }
}

You have to apply an index and set the unique property to true. By default, indexes are non-unique according to documentation.

And also you have to install the Entity Framework 6.1 NuGet package in your project in order to use the new API for indexes.

Note about code-first implementations: A VARCHAR(MAX) cannot be part of a unique constraint. You must specify the maximum length either as a Data Annotation or in the Fluent API.

Leave a Comment