简体   繁体   English

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

[英]Entity Framework Core: How to dynamically get the DbSet from a derived Type?

I have the following abstract class, named Sector : 我有以下抽象类,名为Sector

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

And a second class, GICSSector , wich inherits from Sector : 第二类GICSSector继承自Sector

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

I have the following DbSet in my DbContext : 我的DbSet中有以下DbContext

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

I am trying to write a generic method to loads data from a CSV file, create the objects on the fly and then store the objects in my SQLLite database: 我正在尝试编写一种通用方法来从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();
    }

}

I use the fluent API to manage the tables: 我使用流畅的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);
}

If I run the code I get the following exception: SQLite Error 1: 'no such table: Sectors' . 如果我运行代码,则会收到以下异常: SQLite错误1:'无此类表:Sectors'

If I check the type with typeof(T) or using myEntity.GetType() I get the same expected result: MyNamespace.GICSSector 如果我使用typeof(T)或使用myEntity.GetType()检查类型, MyNamespace.GICSSector得到相同的预期结果: MyNamespace.GICSSector

Why EF Core wants to store it in a table called "Sectors" (the base type) and not in the expected GICSSectors? 为什么EF Core要将其存储在名为“ Sectors”(基本类型)的表中,而不是存储在预期的GICSSectors中?

How can I fix it? 我该如何解决?

Note : The method is a generic one that won't be used to handle only classes that inherit from Sector . 注意 :该方法是一种通用方法,不会仅用于处理从Sector继承的类。

Tell EF explicitly what table to use: 明确告知EF使用哪个表:

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

or use fluent api: 或使用流利的api:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM