我将客户数据存储在两个不同的数据库中。记录保持同步并共享多个字段(例如CustomerId,CustomerName等)。但他们每个人都有自己独特的领域......例如:
Database1客户
CustomerId
CustomerName
Field1
Field2
Database2客户
CustomerId
CustomerName
DifferentField1
DifferntField2
每个数据库都有自己的dbContext,我可以独立地从中拉出每个Customer对象。但我真正想要的是使用单个dbContext将所有字段拉入统一的Customer对象,该对象包括两个dbs中所有字段的并集。这是可能的还是可取的?
我的上下文中的其余对象使用DbSets自动连接并为每个实体指定映射,如下所示:
public DbSet<Customer> Customers { get; set; }
然后我的映射类具有典型的映射信息:
this.ToTable("Customer");
this.HasKey(t => t.CustomerId);
this.Property(t => t.CustomerName);
this.Property(t => t.Field1);
etc.
所以我想知道是否有一种方法可以使用多个表/数据库构建此逻辑,并且不仅可以执行选择,还可以执行所有必需的CRUD操作。这是否可以通过覆盖默认行为来实现?或者我是否会根据问题解决这个问题?
感谢
答案 0 :(得分:2)
您应该考虑将数据库上下文抽象为存储库。因此,您的存储库负责将来自不同层的所有数据编组到单个对象中供您使用,然后每个DBContext仅负责其特定层。
public CustomerRepository
{
public Customer GetCustomerFor(int customerId)
{
var tier1Obj = Tier1DBContext.Customers.First(x => x.CustomerId == customerId);
var tier2Obj = Tier2DBContext.Customers.First(x => x.CustomerId == customerId);
// merge them into some new object
return mergedCustomerObject;
}
}
除非您从数据库本身进行某种链接服务器调用并在一个上下文中公开该值(我不建议这样做),否则不会出现两层错误。