簡體   English   中英

實體框架獨特的關鍵,流暢的api?

[英]Entity Framework unique key with fluent 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 }));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM