c# - EF Core:将 DbContext 实体拆分为多个表
问题描述
我正在尝试使用 EntityFramework Core 来存储共享相同模型但来源不同的实体。我有一个ProductType
指定实体类型的枚举。
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;}
}
我正在使用派生DbContext
与 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}" );
}
}
我希望每个ProductType
都被拆分到自己的表中,因此产品将存储在dbo.Products-Digital
、dbo.Products-Furniture
和dbo.Products-Health
.
上述实现适用于单个ProductType
,但是当我尝试为多个表创建表时,我开始遇到问题。运行以下(显然)会导致问题,因为它只会为第一次ProductType
遇到的创建一个表,因为在那之后已经创建了数据库:
var types = Enum.GetValues( typeof(ProductType) ).Cast<ProductType>();
foreach( var type in types )
{
var context = new ProductDbContext( type );
context.Database.EnsureCreated();
}
我希望能够ProductType
随着时间的推移添加新值,并让 EFCore 自动为每个表创建表(如果它们尚不存在)。
那么,如何让 EF Core 自动确保每个表都存在一个表ProductType
,包括我稍后添加的表?
解决方案
推荐阅读
- go - 我可以在 go 中使用什么数字类型来获得最大的数字?
- python - azure databricks 中的表不会更新或覆盖其内容。我如何使用 python 代码以编程方式做到这一点?
- asp.net - 未处理的异常未登录 appinsights
- c++ - 是否可以从另一个类对象调用一个类函数而不继承第一个类
- android - Android:CalendarProvider 事件未创建,有时在创建后消失(在少数设备中)
- google-apps-script - 第一次匹配后谷歌脚本停止循环
- angularjs - 如何将控制器绑定到指令?
- javascript - 替代 Textfield onChange 的行为类似于 HTML onChange?
- swift - Swift 5.0“设置”允许重复值
- javascript - 除某些点击事件外,Mat-Menu 上的 StopPropagation - Angular