c# - Entity Framework 核心 : How to dynamically get the DbSet from a derived Type?

标签 c# entity-framework entity-framework-core

我有以下抽象类,名为 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 要将其存储在名为“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/

相关文章:

c# - 无法使用 AsyncEntitySetController 为单个 OData 实体获取 $expand

c# - .net 中的透明用户控制

c# - 保持库无依赖性

sql-server - Entity Framework 6 数据库优先方法不从 SQL Server 创建所有表

view - 如何在带有 Entity Framework Core 1.0 (EF7) 的脚手架 DbContext 中使用数据库 View

c# - 如何将文件从 UNC 共享复制到本地系统?

c# - Entity Framework - 保存引用新记录的外键

c# - Entity Framework : How to perform left join with EF and LINQ among multiple tables

.net - dotnet ef 迁移列表在迁移文件夹中找不到迁移

c# - Entity Framework Core 不尊重标识列