[英]Entity Framework updating two databases
As I've mentioned in a couple other questions, I'm currently trying to replace a home-grown ORM with the Entity Framework, now that our database can support it. 正如我在其他几个问题中提到的那样,由于我们的数据库可以支持它,所以我目前正在尝试用Entity Framework替换自家的ORM。
Currently, we have certain objects set up such that they are mapped to a table in our internal database and a table in the database that runs our website (which is not even in the same state, let alone on the same server). 目前,我们有一定的对象设置,使得它们映射到我们的内部数据库中的表和数据库中的表运行我们的网站(这是不是即使在同一个国家,如果单独让同一台服务器上)。 So, for example:
因此,例如:
Part p = new Part(12345);
p.Name = "Renamed part";
p.Update();
will update both the internal and the web databases simultaneously to reflect that the part with ID 12345 is now named "Renamed part". 将同时更新内部数据库和Web数据库,以反映ID为12345的零件现在被命名为“重命名零件”。 This logic only needs to go one direction (internal -> web) for the time being.
这种逻辑暂时只需要走一个方向(内部->网络)。 We access the web database through a LINQ-to-SQL DBML and its objects.
我们通过LINQ-to-SQL DBML及其对象访问Web数据库。
I think my question has two parts, although it's possible I'm not asking the right question in the first place. 我认为我的问题分为两个部分,尽管我可能没有一开始就提出正确的问题。
.SaveChanges()
and when it hits the database? .SaveChanges()
和它命中数据库之间插入逻辑? 听起来像是Sql Server复制的工作 。
您不需要像问题2那样将两者相互连接在一起。只需将两个单独的数据库具有自己的EF或L2S模型,然后使用具有域对象的存储库将它们抽象化即可。
This is the solution I ended up going with. 这就是我最终要解决的问题。 Note that the implementation of
IAdvantageWebTable
is inherited from the existing base class, so nothing special needed to be done for EF-based classes, once the T4 template was modified to inherit correctly. 请注意,
IAdvantageWebTable
的实现是从现有的基类继承的,因此,一旦将T4模板修改为正确继承,对于基于EF的类就无需进行任何特殊处理。
public partial class EntityContext
{
public override int SaveChanges(System.Data.Objects.SaveOptions options)
{
var modified = this.ObjectStateManager.GetObjectStateEntries(EntityState.Modified | EntityState.Added); // Get the list of things to update
var result = base.SaveChanges(options); // Call the base SaveChanges, which clears that list.
using (var context = new WebDataContext()) // This is the second database context.
{
foreach (var obj in modified)
{
var table = obj.Entity as IAdvantageWebTable;
if (table != null)
{
table.UpdateWeb(context); // This is IAdvantageWebTable.UpdateWeb(), which calls all the existing logic I've had in place for years.
}
}
context.SubmitChanges();
}
return result;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.