使用Fluent API创建Entity Framework的唯一键?

3
有没有一种方法可以使用Fluent API指定索引应该是唯一的,而不必将其作为数据注释添加到模型本身中?
public class RecordType
{
    public int Id { get; set; }

    [Index(IsUnique = true)]
    public string RecordType { get; set; }
}

如何在下面的代码中添加唯一索引?

public class RecordTypeConfiguration : EntityTypeConfiguration<RecordType>
{
    public RecordTypeConfiguration()
    {
       HasKey(i => i.Id);
       Property(e => e.RecordType).HasColumnType("VARCHAR").HasMaxLength(1);   
    }
}
2个回答

4
在实体框架>=6.2中,
在DbContext中:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
     base.OnModelCreating(modelBuilder);

     modelBuilder.Entity<RecordType>().HasIndex(u => u.RecordType).IsUnique();
}

在 Entity Framework < 6.2 中,
在 DbContext 中:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
     base.OnModelCreating(modelBuilder);

     modelBuilder.Entity<RecordType>().Property(t => t.RecordType).HasMaxLength(1)
                                  .HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute("Ix_RecordType"){IsUnique = true}));
}

或者在单独的配置文件中:

public class RecordTypeConfiguration : EntityTypeConfiguration<RecordType>
{
    public RecordTypeConfiguration()
    {
        HasKey(i => i.Id);

        Property(e => e.RecordType).HasColumnType("VARCHAR").HasMaxLength(1);

        Property(t => t.RecordType).HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute("Ix_RecordType"){IsUnique = true}));

     }
}

0

我猜你可以使用IndexAttribute:

   this.Property(t => t.RecordType)
   .HasColumnAnnotation(
   "Index",
   new IndexAnnotation(new IndexAttribute("_RecordType") { IsUnique = true }));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接