繁体   English   中英

EF代码优先将唯一索引添加到列

[英]EF Code-First Add Unique Index to Column

在我的实体框架代码优先模型中,我有一个表,该表需要一个列才能具有唯一值。 我想对其应用唯一索引,因为我发现它在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);
}

如您所见,索引在这里不是唯一的。

此外,数据库索引还告诉您创建的索引不是唯一的

无唯一SQL索引

我看到在EF的旧版本中,您必须通过Model Builder进行此操作,我也尝试过:

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.Linq。 Expressions.Expression>)

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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