Creating Unique Index with Entity Framework 6.1 fluent API

.net c# entity-framework entity-framework-6 fluent-interface

Question

My "Name" field demands uniqueness. There is no foreign key or anything similar.

Finally, EF 6.1 supports building these indexes using Annotations. On SO, that has already been covered. However, it appears that the only way to do that is through class annotations. How can I accomplish that using just the Fluent API?

Possibly 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();  //???
    }
}
1
38
2/27/2017 8:03:14 AM

Accepted Answer

NOTE: Concerning EF 6

You may utilizeIndexAttribute as already indicated, however with Fluent APIDataAnnotations which will be effective:

modelBuilder 
    .Entity<Person>() 
    .Property(t => t.Name) 
    .HasColumnAnnotation( 
        "Index",  
        new IndexAnnotation(new IndexAttribute("IX_Name") { IsUnique = true }));

Unfortunately, there is no other method to utilizing to construct unique indexes.Fluent API . Regarding this feature, there is an unresolved matter: Unique Restrictions (Unique Indexes)


Entity Framework Core Update

You can rely on Fluent API providing indexes in the most recent EF Core version without using any special techniques.
HasIndex enables one to define it:
modelBuilder 
    .Entity<Person>()
    .HasIndex(x => x.Name);

Thus, it returns.IndexBuilder You can utilize the object for additional index configurations (such as uniqueness):

modelBuilder 
    .Entity<Person>()
    .HasIndex(x => x.Name)
    .IsUnique();
58
5/16/2018 11:47:07 AM

Popular Answer

Here is an extension way for setting unique indexes more fluidly based on Anatolii's response:

public static class MappingExtensions
{
    public static PrimitivePropertyConfiguration IsUnique(this PrimitivePropertyConfiguration configuration)
    {
        return configuration.HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute { IsUnique = true }));
    }
}

Usage:

modelBuilder 
    .Entity<Person>() 
    .Property(t => t.Name)
    .IsUnique();

resulting in migration such as:

public partial class Add_unique_index : DbMigration
{
    public override void Up()
    {
        CreateIndex("dbo.Person", "Name", unique: true);
    }

    public override void Down()
    {
        DropIndex("dbo.Person", new[] { "Name" });
    }
}


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow