具有流畅 API 的实体框架唯一键?



有没有办法使用 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);   
}
}

在实体框架>= 6.2 中,

在 DbContext 中:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<RecordType>().HasIndex(u => u.RecordType).IsUnique();
}

在实体框架 <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}));
}
}

我想你可以使用IndexAttribute:

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

最新更新