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?