我正在尝试在我的项目中实现DDD。 我在每个解决方案中都有不同的解决方案(每个Bounded Context)和dbcontext。 与产品和客户管理的Master.sln以及SalesOrder Management的SalesOrder.sln类似。
问题在于,当我已经为Master迁移并尝试使用Contact和Product在SalesOrder中配置外键时(Contact是RetailContact,Product是SalesOrderDbContext中的RetailProduct)迁移正在为Product和Customer Table生成脚本因为我已经在我的数据库中有产品和客户(通过MasterDbContext更新),所以在更新我的数据库时会发生冲突。忽略产品和客户时,未配置外键。
我正在寻找一种在多个DbContext中配置外键关系的方法,同时忽略不同DbContext中已经创建的表。
MasterDbContext
public MasterDbContext(DbContextOptions<MasterDbContext> options) : base((DbContextOptions)options)
{
}
public DbSet<Product> Products { get; set; }
public DbSet<ProductCategory> ProductCategories { get; set; }
public DbSet<WareHouse> WareHouses { get; set; }
public DbSet<Contact> Contacts { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema("Master");
base.OnModelCreating(modelBuilder);
}
}
SalesOrder.sln中的SalesOrderDbContent
public class SalesOrderDbContext : DbContext
{
public SalesOrderDbContext(DbContextOptions<SalesOrderDbContext> options) : base(options)
{
}
public DbSet<RetailMilkOrder> RetailMilkOrders { get; set; }
public DbSet<DistributorOrder> DistributorOrders { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<WareHouse>().ToTable("WareHouses");
modelBuilder.Entity<RetailContact>().ToTable("Contacts");
modelBuilder.Entity<RetailProduct>().ToTable("Products");
modelBuilder.Ignore<RetailProduct>();
modelBuilder.HasDefaultSchema("SalesOrder");
modelBuilder.ApplyConfiguration(new RetailMilkOrderConfiguration());
modelBuilder.ApplyConfiguration(new RetailMilkOrderItemConfiguration());
base.OnModelCreating(modelBuilder);
}
}
public class RetailMilkOrderItemConfiguration : IEntityTypeConfiguration<RetailMilkOrderItem>
{
public void Configure(EntityTypeBuilder<RetailMilkOrderItem> itemConfig)
{
itemConfig.ToTable("RetailMilkOrderItems");
itemConfig.HasOne<RetailProduct>()
.WithMany()
.HasForeignKey(itm =>itm.RetailProductId);
}
}
public class RetailMilkOrderConfiguration : IEntityTypeConfiguration<RetailMilkOrder>
{
public void Configure(EntityTypeBuilder<RetailMilkOrder> orderConfig)
{
orderConfig.OwnsOne(o => o.RetailOrderDateSpec);
orderConfig.Metadata.FindNavigation(nameof(RetailMilkOrder.Items)).SetPropertyAccessMode(PropertyAccessMode.Field);
orderConfig.HasOne<RetailContact>()
.WithMany()
.HasForeignKey(i => i.RetailerId);
orderConfig.HasOne<WareHouse>()
.WithMany()
.HasForeignKey(o => o.WareHouseId);
}
}
请建议我拆分多个Dbcontext并保持Model SnapShot同步的方法。