我有以下抽象类,名为 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/