简体   繁体   English

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

[英]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 我想对其应用唯一索引,因为我发现它在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: 我看到在EF的旧版本中,您必须通过Model Builder进行此操作,我也尝试过:

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>) 类型'kData.Sharepoint'必须是不可为空的值类型,以便在通用类型或方法'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? 那么,如何在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. 可能是因为您正在对数据库中不存在的导航属性指定唯一约束,但是数据库上存在外键,因此您可以尝试将属性应用于外键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