2017-02-24 49 views
5

我有以下的抽象類,命名爲Sector實體框架核心:如何從派生類型動態獲取DbSet?

public abstract class Sector 
{ 
    public string ID {get; set;} 
    public string Name {get; set;} 
    public Sector(){} 
} 

而第二類,GICSSector,至極從Sector繼承:

public class GICSSector: Sector 
{ 
    public virtual ICollection<GICSIndustryGroup> IndustryGroups {get; set;} 
} 

我已經在我的DbContext以下DbSet

public DbSet<GICSSector> GICSSectors {get; set;} 

我想寫一個通用的方法來加載d ATA從CSV文件,動態創建的對象,然後將對象存儲在我的SQLLite數據庫:

public static void UpdateEntitiesFromCSV<T>(MyContextFactory factory, string fileName) where T : class 
{ 
    var entities = new List<T>(); 

    // ... Load entities from the CSV 
    // ... Create the objects and add them to the list 

    // Add the objects to the database 

    using (var db = factory.Create(new DbContextFactoryOptions())) 
    { 
     var set = db.Set<T>(); 

     foreach(T e in entities) 
     { 
      set.Add(e); 
     } 

     db.SaveChanges(); 
    } 

} 

我用流利的API來管理表:

protected override void OnModelCreating(ModelBuilder modelBuilder) 
{ 
    //... 

    // GICSSector  
    modelBuilder.Entity<GICSSector>().HasKey(s => new { s.ID }); 
    modelBuilder.Entity<GICSSector>().Property(s => s.ID).HasMaxLength(2);  
    modelBuilder.Entity<GICSSector>().Property(s => s.Name).IsRequired();  
    modelBuilder.Entity<GICSSector>().Property(s => s.Name).HasMaxLength(50); 
} 

如果我運行代碼我得到以下異常:SQLite錯誤1:'沒有這樣的表:部門'

如果我檢查的類型與typeof(T)或使用myEntity.GetType(),我得到了相同的預期結果:MyNamespace.GICSSector

爲什麼EF核心希望將其存儲在一個名爲「部門」(基本型),而不是預期的表GICSSectors?

我該如何解決?

注意:該方法是一個通用的方法,不會用於處理僅從Sector繼承的類。

+0

註釋與TableAttribute的GICSSector類? – MarkB

+0

我使用流利的API,我更新了問題 –

+0

然後用流利的API來設置表名? (看我的回答) – MarkB

回答

0

告訴EF明確使用什麼表:

[Table("GICSSectors")] 
public class GICSSector: Sector 
{ 
    public virtual ICollection<GICSIndustryGroup> IndustryGroups {get; set;} 
} 

,或者使用流暢API:

modelBuilder.Entity<GICSSector>().ToTable("GICSSectors");