小编典典

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

c#

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


阅读 454

收藏
2020-05-19

共1个答案

小编典典

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

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

modelBuilder
    .Entity<User>()
    .HasIndex(u => u.Email)
        .IsUnique();

EF6.1 开始,您可以使用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 }));
2020-05-19