EF Code-First Add Unique Index to Column

c# entity-framework entity-framework-6 indexing unique

Question

I have a table in my entity-framework code-first model that requires one column to contain unique values. I want to add a Unique Index to it because I saw that EF 6.1 makes it extremely simple to do so.

public partial class User
{
   public int Id { get; set; }

   [Index(IsUnique = true)]
   public virtual SharePoint SharePoint { get; set; }
}

The following is produced when a migration for this code is created:

public override void Up()
{
    CreateTable(
        "dbo.Users",
        c => new
            {
                Id = c.Int(nullable: false, identity: true),
                SharePoint_Id = c.Int(nullable: false),
            })
        .PrimaryKey(t => t.Id)
        .ForeignKey("dbo.SharePoints", t => t.SharePoint_Id)
        .Index(t => t.SharePoint_Id);
}

The Index is not Unique, as you can see.

Additionally, the constructed index's DB Indices indicate that it is not unique.

None Unique SQL Index

I noticed that you have to perform this through the Model Builder in earlier versions of EF, so I gave it a shot:

modelBuilder.Entity<Configuration>()
    .Property(p => p.SharePoint)
    .HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute() { IsUnique = true }));

which regrettably leads to the error:

The type 'kData.Sharepoint' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'System.Data.Entity.ModelConfiguration.Configuration.StructuralTypeConfiguration.Property (System.Linq.Expressions.Expression>)

So how can one add a unique index to a column in EF 6.1 using a code-first migration?

1
2
4/23/2015 1:24:23 PM

Popular Answer

This is likely because you are setting a unique constraint on the navigation property, but the database really has a foreign key for that property, therefore you might try applying an attribute to that foreign key.SharePoint_Id and make it non-nullable, after which it ought to function.

modelBuilder.Entity<User>()
.Property(p => p.SharePoint_Id)
.HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute() { IsUnique = true }));
0
4/23/2015 1:20:45 PM


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