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



我有以下抽象类,名为 Sector

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;}

我正在尝试编写一个通用方法来加载来自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 Core要将其存储在称为"扇区"(基本类型)而不是预期的GICSSECTORS的表中?

我该如何修复?

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

明确地告诉ef:

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

或使用流利的API:

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

相关内容

最新更新