EF Core: Splitting up DbContext entities into multiple tables

c# entity-framework entity-framework-core

Question

I am trying to use EntityFramework Core to store entities that share the same model but are of different origins. I have a ProductType enum that designates the type of the entity.

public enum ProductType
{
  Digital,
  Furniture,
  Health,
}

public class ProductModel
{
  public int Id {get; set;}
  public ProductType Type {get;set;}
  public decimal Price {get; set;}
  public int Stock {get;set;}
}

I am using a derived DbContext to interact with SqlServer Express:

public class ProductDbContext : DbContext
{
  public ProductType ProductType { get; }
  public DbSet<ProductModel> Products { get; }

  public ProductDbContext( ProductType type )
  {
    ProductType = type;
  }

  protected override void OnModelCreating( ModelBuilder modelBuilder )
  {
    var productEntity = modelBuilder.Entity<ProductModel>()
       .ToTable( $"Products-{ProductType}" );
  }
}

I want each ProductType to be split into its own table, so products would be stored in dbo.Products-Digital, dbo.Products-Furniture, and dbo.Products-Health.

The above implementation works for a single ProductType, but I start running into issues when I try to create a table for more than one. Running the following (obviously) causes issues, since it will only create a table for the first ProductType encountered, since the database is already created after that:

var types = Enum.GetValues( typeof(ProductType) ).Cast<ProductType>();
foreach( var type in types )
{
  var context = new ProductDbContext( type );
  context.Database.EnsureCreated();
}

I would like to be able to add new ProductType values as time goes on and have EFCore automatically create tables for each one if they don't already exist.

So, how can I get EF Core to automatically ensure that a table exists for each ProductType, including ones I add later on?

1
0
3/7/2019 9:49:11 PM

Accepted Answer

This is an example of the table per type inheritance model which isn't currently supported by EF Core, you should consider switching to the table per hierarchy model which is supported and can be configured via the Fluent API.

https://docs.microsoft.com/en-us/ef/core/modeling/relational/inheritance

0
3/7/2019 10:03:32 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow