实体框架核心:如何从派生类型动态获取DbSet?

Nic*_*ada 5 c# entity-framework entity-framework-core

我有以下抽象类,命名为Sector:

public abstract class Sector
{
    public string ID {get; set;}
    public string Name {get; set;}
    public Sector(){}
 }
Run Code Online (Sandbox Code Playgroud)

第二类,GICSSector继承自Sector:

public class GICSSector: Sector
{
   public virtual ICollection<GICSIndustryGroup> IndustryGroups {get; set;}
}
Run Code Online (Sandbox Code Playgroud)

我有以下DbSetDbContext:

public DbSet<GICSSector> GICSSectors {get; set;}
Run Code Online (Sandbox Code Playgroud)

我正在尝试编写一个通用方法来从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();
    }

}
Run Code Online (Sandbox Code Playgroud)

我使用流畅的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);
}
Run Code Online (Sandbox Code Playgroud)

如果我运行代码,我会得到以下异常:SQLite错误1:'没有这样的表:Sectors'.

如果我使用typeof(T)或使用我检查类型,myEntity.GetType()我得到相同的预期结果:MyNamespace.GICSSector

为什么EF Core希望将它存储在名为"Sectors"(基本类型)的表中而不是在预期的GICSSectors中?

我该如何解决?

注意:该方法是一个通用方法,不会用于仅处理从中继承的类Sector.

Mar*_*rkB -1

明确告诉 EF 使用哪个表:

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

或使用流畅的API:

modelBuilder.Entity<GICSSector>().ToTable("GICSSectors");   
Run Code Online (Sandbox Code Playgroud)