2

我有一個基類,有一些屬性和行爲。這個基類被許多其他類擴展/繼承。其中一些類應該在其自己的屬性之一和基類的一個屬性上創建唯一的多列索引。在繼承的非重寫字段上的多列索引

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爲虛擬(因此仍然在所有子類中實現),並在用於多列索引定義的類(以及對基本實現的調用)中覆蓋它?

親切的問候, 隊友

+0

請仔細閱讀並考慮修改您的標題以刪除標籤:http://meta.stackexchange.com/questions/19190/should-questions-include-tags-in-their-titles –

回答

1

你將不得不使用註釋跳過並使用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);    
    }