[英]Entity Framework Core: How to dynamically get the DbSet from a derived Type?
我有以下抽象類,名為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;}
}
我的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
得到相同的預期結果: 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");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.