NOTE: Relevant to EF 6
You can use IndexAttribute
as mentioned but with Fluent API
instead of DataAnnotations
which will do the trick:
modelBuilder
.Entity<Person>()
.Property(t => t.Name)
.HasColumnAnnotation(
"Index",
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)
UPDATE: Entity Framework Core
In the latest EF Core release you can rely on
Fluent API
to specify indexes without additional tricks.
HasIndex
allows to define it:
modelBuilder
.Entity<Person>()
.HasIndex(x => x.Name);
Hence it returs IndexBuilder
object you can use it for further index configurations (i.e uniqueness):
modelBuilder
.Entity<Person>()
.HasIndex(x => x.Name)
.IsUnique();
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…