使用流畅的API设置唯一约束?

我正在尝试使用Code First和EntityTypeConfiguration使用流畅的API

构建EF实体。创建主键很容易,但是使用唯一约束则不容易。我看到的旧文章建议为此执行本机SQL命令,但这似乎无法达到目的。EF6有可能吗?

回答:

在 ,您可以HasIndex()用来添加索引以通过fluent API进行迁移。

https://github.com/aspnet/EntityFramework6/issues/274

modelBuilder

.Entity<User>()

.HasIndex(u => u.Email)

.IsUnique();

从 开始,您可以使用IndexAnnotation()fluent API添加用于迁移的索引。

http://msdn.microsoft.com/zh-

cn/data/jj591617.aspx#PropertyIndex

您必须添加对以下内容的引用:

using System.Data.Entity.Infrastructure.Annotations;

这是一个简单的用法,在User.FirstName属性上添加索引

modelBuilder 

.Entity<User>()

.Property(t => t.FirstName)

.HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute()));

这是一个更现实的例子。它将在多个属性上添加 :User.FirstNameUser.LastName,索引名称为“

IX_FirstNameLastName”

modelBuilder 

.Entity<User>()

.Property(t => t.FirstName)

.IsRequired()

.HasMaxLength(60)

.HasColumnAnnotation(

IndexAnnotation.AnnotationName,

new IndexAnnotation(

new IndexAttribute("IX_FirstNameLastName", 1) { IsUnique = true }));

modelBuilder

.Entity<User>()

.Property(t => t.LastName)

.IsRequired()

.HasMaxLength(60)

.HasColumnAnnotation(

IndexAnnotation.AnnotationName,

new IndexAnnotation(

new IndexAttribute("IX_FirstNameLastName", 2) { IsUnique = true }));

以上是 使用流畅的API设置唯一约束? 的全部内容, 来源链接: utcz.com/qa/409500.html

回到顶部