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

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

第二类GICSSectorSector继承:
public class GICSSector: Sector
{
   public virtual ICollection<GICSIndustryGroup> IndustryGroups {get; set;}
}

我的DbSet中有以下DbContext:
public DbSet<GICSSector> GICSSectors {get; set;}

我正在尝试编写一种通用方法来从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:'无此类表:Sectors'

如果我使用typeof(T)myEntity.GetType()检查类型,则得到相同的预期结果:MyNamespace.GICSSector
为什么EF Core要将其存储在名为“Sectors”(基本类型)的表中,而不是存储在预期的GICSSectors中?

我该如何解决?

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

最佳答案

明确告诉EF要使用哪个表:

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

或使用流利的api:
modelBuilder.Entity<GICSSector>().ToTable("GICSSectors");

关于c# - Entity Framework 核心: How to dynamically get the DbSet from a derived Type?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42438589/

10-09 09:30