EF Code-First Add Unique Index to Column

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

Question

In my Entity-Framework Code-First Model I have a Table that needs one column to have unique values. I want to apply an Unique Index to it as I saw that it is very easy in EF 6.1

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

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

When creating a migration for this code the following is being generated:

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);
}

As you can see, the Index is not Unique here.

Also the DB Indices tell that the created index is not unique

None Unique SQL Index

I saw in older versions of EF that you had to do this via the Model Builder, which I tried aswell:

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

Which sadly results in 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 is it possible to create a code-first migration, adding an Unique Index to a Column in EF 6.1?

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

Popular Answer

Probably this is because you are specifying Unique constraint on navigation property that does not exist in the database rather it's foreign key is there on database so you may try applying attribute to foreign key SharePoint_Id and make it not nullable and then it should work.

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