EF Code-First向列添加唯一索引

时间:2015-04-23 13:12:50

标签: c# entity-framework indexing entity-framework-6 unique

在我的实体框架代码优先模型中,我有一个表需要一列具有唯一值。我想对它应用唯一索引,因为我看到它在EF 6.1中非常容易

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

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

为此代码创建迁移时,会生成以下内容:

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

正如您所看到的,索引此处为唯一。

DB Indices也表示创建的索引不是唯一的

None Unique SQL Index

我在EF的旧版本中看到,您必须通过模型构建器执行此操作,我尝试过这样做:

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

遗憾地导致错误:

  

类型'kData.Sharepoint'必须是非可空值类型才能在泛型类型或方法'System.Data.Entity.ModelConfiguration.Configuration.StructuralTypeConfiguration.Property(System)中将其用作参数'T' .Linq.Expressions.Expression&GT)

那么如何创建代码优先迁移,在EF 6.1中为列添加唯一索引呢?

1 个答案:

答案 0 :(得分:0)

可能这是因为您在导航属性上指定了对数据库中不存在的唯一约束,而不是数据库中存在外键,因此您可以尝试将属性应用于外键SharePoint_Id并进行制作它不可空,然后它应该工作。

modelBuilder.Entity<User>()
.Property(p => p.SharePoint_Id)
.HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute() { IsUnique = true }));
相关问题