首页 > 解决方案 > 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-Digitaldbo.Products-Furnituredbo.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,包括我稍后添加的表?

标签: c#entity-frameworkentity-framework-core

解决方案


推荐阅读