简体   繁体   中英

EF Code-First Add Unique Index to Column

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

无唯一SQL索引

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM