我在实体框架中为两个不同的数据库创建了两个不同的上下文。现在,我试图在单个事务中更新这些数据库。我的代码是这样的
public class LPO_BLL
{
internal Context1 _context1 = null;
internal Context2 _Context2 = null;
public LPO_Detail_BLL(Context1 context1, Context2 context2)
{
_context1 = context1;
_context2 = context2;
}
public void Insert(PM_LPO lpo, LPO_Transaction lpo_transaction)
{
using (TransactionScope transaction = new TransactionScope())
{
_context1.LPO.Add(lpo);
_context1.SaveChanges();
_context2.LPO_Transaction.Add(lpo_transaction);
_context2.SaveChanges(); // I am getting error here...
transaction.Complete();
}
}
}在UI项目中,我称之为:
LPO lpo = new LPO();
//setting properties of lpo
LPO_Transaction lpo_trans = new LPO_Transaction();
//setting properties of lpo_trans
Context1 _context1 = new Context1();
//Opening _context1 connection and etc
Context2 _context2 = new Context2();
//Opening _context2 connection and etc
LPO_BLL lpo_bll = new LPO_BLL(_context1, _context2);
lpo_bll.Insert(lpo,lpo_trans);目前,我遇到了错误:底层提供者EnlistTransaction失败了
在互联网上搜索了3个小时,尝试了不同的攻击和测试方法之后,我决定把它戴上。到目前为止,我发现这两个联系有点接近:
http://social.msdn.microsoft.com/Forums/en-US/3ccac6f7-6513-4c87-828a-00e0b88285bc/the-underlying-provider-failed-on-enlisttransaction?forum=adodotnetentityframework
TransactionScope - The underlying provider failed on EnlistTransaction. MSDTC being aborted
发布于 2013-12-09 10:40:47
并非所有DB提供程序都支持分布式事务。
使用事务作用域将尝试在MSDTC管理的分布式事务处理中登记DB事务。如果您的提供者不支持这一点,它将失败。
Server和Oracle提供程序支持分布式事务。但许多其他EF供应商却不这么做。
如果您的DB提供程序支持这一点,您将不得不使用另一个或放弃使用事务。
如果您使用的是Server 2005,则它应该可以工作,但是:
看看this SO Q&A: confusion about transactions and msdtc。
注意:服务的名称是MSDTC。这样您就可以运行net start msdtc或net stop msdtc。如果您在控制面板中查找它,您将找到一个描述性名称,如“分布式事务协调器”或本地化名称,如“协调员de transacciones distribuidas”。奇怪的是,无法在本地服务的控制面板列表中显示name列。
发布于 2015-06-17 15:54:26
为了在参数中使用ObjectContext,必须在DbContext中使用SaveChanges:
public class EntityDBContext: DbContext, IObjectContextAdapter
{
ObjectContext IObjectContextAdapter.ObjectContext {
get {
return (this as IObjectContextAdapter).ObjectContext;
}
}
}然后在插入方法中,使用:
public void Insert(PM_LPO lpo, LPO_Transaction lpo_transaction)
{
using (TransactionScope transaction = new TransactionScope())
{
context1.ObjectContext.SaveChanges(false);
context2.ObjectContext.SaveChanges(false);
_context1.LPO.Add(lpo);
_context2.LPO_Transaction.Add(lpo_transaction);
transaction.Complete();
context1.ObjectContext.AcceptAllChanges();
context2.ObjectContext.AcceptAllChanges();
}
}发布于 2013-12-09 11:23:34
对于多个数据库,应该使用Savechange(false)和AcceptAllChanges()。
public void Insert(PM_LPO lpo, LPO_Transaction lpo_transaction)
{
using (TransactionScope transaction = new TransactionScope())
{
context1.SaveChanges(false);
context2.SaveChanges(false);
_context1.LPO.Add(lpo);
_context2.LPO_Transaction.Add(lpo_transaction);
transaction.Complete();
context1.AcceptAllChanges();
context2.AcceptAllChanges();
}
}https://stackoverflow.com/questions/20468245
复制相似问题