继承的、未覆盖的字段上的多列索引

本文关键字:索引 覆盖 继承 字段 | 更新日期: 2023-09-27 18:32:50

我有一个基类,其中包含一些属性和行为。此基类由许多其他类扩展/继承。其中一些类应该在它们自己的一个属性和基类的一个属性上创建一个唯一的多列索引。

public class BaseClass
{ 
    long employeeId {get; set;}
    // and many other things...
}
public class Buzzword : BaseClass
{
    string Name {get;set;} // supposed to be unique for every employee
    // many other things...
}

我现在想做的是这样的,重复我的流行语课:

public class Buzzword : BaseClass
{
    [Index("IX_Buzzword_EmployeeId_Name", IsUnique = true, Order = 1]
    // black magic: inherited property of BaseClass
    [Index("IX_Buzzword_EmployeeId_Name", IsUnique = true, Order = 2]
    string Name {get;set;} // supposed to be unique for every employee
    // many other things...
}

我该怎么做?使 employeeId 成为虚拟(因此仍在所有子类中实现)并在类中覆盖它以进行多列索引定义(以及对基本实现的调用)?

亲切问候伴侣

继承的、未覆盖的字段上的多列索引

如果基类包含多列索引中所需的列,则必须跳过使用注释并使用EntityTypeConfiguration进行映射。

因此,在 DbContext 中,您可以执行以下操作:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<BuzzWord>().Property(b => b.EmployeeId).HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute("IX_Buzzword_EmployeeId_Name", 1)));
        modelBuilder.Entity<BuzzWord>().Property(b => b.Name).HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute("IX_Buzzword_EmployeeId_Name", 2)));
        base.OnModelCreating(modelBuilder);
    } 

或者,如果您不喜欢用大量映射代码污染 DbContext,则可以创建一个映射类并告诉您的上下文加载所有这些映射类:

public class BuzzWordMapping : EntityTypeConfiguration<BuzzWord>
{
    public BuzzWordMapping()
    {
        Property(b => b.EmployeeId).HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute("IX_Buzzword_EmployeeId_Name", 1)));
        Property(b => b.Name).HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute("IX_Buzzword_EmployeeId_Name", 2)));
    }
}

那么你的OnModelCreating将如下所示:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        //  This should include any mappings defined in the same assembly as the BuzzWordMapping class
        modelBuilder.Configurations.AddFromAssembly(typeof(BuzzWordMapping).Assembly);
        base.OnModelCreating(modelBuilder);            
    }