【发布时间】:2015-07-01 16:52:21
【问题描述】:
在我的实体框架代码优先模型中,我有一个表,它需要一列才能具有唯一值。我想对其应用唯一索引,因为我看到它在 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);
}
如您所见,索引在此处不是唯一的。
数据库索引也表明创建的索引不是唯一的
我在旧版本的 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(系统.Linq.Expressions.Expression>)
那么如何创建代码优先迁移,在 EF 6.1 中向列添加唯一索引?
【问题讨论】:
-
@Prokurors 这些仅描述错误消息。正如您在表的声明中所见,字段
SharePoint不被指定为可为空。我认为其他的东西,可能是内部的 EF,这里是错误的
标签: c# entity-framework indexing entity-framework-6 unique