Entity Framework Core: How to dynamically get a DbSet from a derived type?

I have the following abstract class called Sector :

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

And the second class is GICSSector , which inherits from Sector :

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

I have a DbSet in a DbContext :

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

I am trying to write a general method for loading data from a CSV file, creating objects on the fly and then storing objects in my SQLLite database:

 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 free API for managing tables:

 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: "there is no such table: sector" .

If I check the type with typeof(T) or using myEntity.GetType() , I get the same expected result: MyNamespace.GICSSector

Why does EF Core want to save it in a table called "Sectors" (the base type), and not in the expected GICSSectors?

How can i fix this?

Note. The method is a general one that will not be used to process only classes that inherit from the Sector .

+5
source share
1 answer

Tell EF explicitly which table to use:

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

or use a quick api:

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

Source: https://habr.com/ru/post/1264682/


All Articles