现有的数据库模式具有唯一的非主键以及一些依赖它们的外键。
是否可以在 Entity Framework v4 中定义唯一键(不是主键)?如何?
实体框架6.1现在支持数据注释和 Fluent API 的唯一性。
数据注释 (参考 http://msdn.microsoft.com/en-us/data/jj591583#Index)
public class MyEntityClass
{
[Index(IsUnique = true)]
[MaxLength(255)] // for code-first implementations
public string MyUniqueProperty{ get; set; }
}
流畅的API (参考 http://msdn.microsoft.com/en-us/data/jj591617.aspx#PropertyIndex)
public class MyContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder
.Entity<MyEntityClass>()
.Property(t => t.MyUniqueProperty)
.HasMaxLength(255) // for code-first implementations
.HasColumnAnnotation(
"Index",
new IndexAnnotation(new[]
{
new IndexAttribute("Index") { IsUnique = true }
})));
}
}
}
您必须应用索引并将 unique 属性设置为 true。默认情况下,根据文档,索引是非唯一的。
此外,您还必须在项目中安装 Entity Framework 6.1 NuGet 包才能使用新的索引 API。
关于代码优先实现的注意事项:AVARCHAR(MAX)
不能是唯一约束的一部分。您必须以数据注释或 Fluent API 的形式指定最大长度。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)