所以,我有两个数据库...... Users数据库和另一个也包含Users表的数据库。两者都有一个电子邮件字段我想同时更新这两个电子邮件字段。
(简化)代码如下所示:
using(var db1 = new Db1Context())
using(var db2 = new Db2Context())
{
db1.Users.Single(u => u.Email == oldEmail).Email = someEmail;
db2.Users.Single(u => u.Email == oldEmail).Email = someEmail;
db1.SaveChanges();
db2.SaveChanges(); //what if this fails?
}
所以,尝试1:
using(var db1 = new Db1Context())
using(var db2 = new Db2Context())
using(var txs = new TransactionScope())
{
db1.Users.Single(u => u.Email == oldEmail).Email = someEmail;
db2.Users.Single(u => u.Email == oldEmail).Email = someEmail;
db1.SaveChanges();
db2.SaveChanges(); //what if this fails?
txs.Complete();
}
以ArgumentException
和以下堆栈跟踪失败:
[ArgumentException: Value does not fall within the expected range.]
System.Transactions.Oletx.IDtcProxyShimFactory.ConnectToProxy(String nodeName, Guid resourceManagerIdentifier, IntPtr managedIdentifier, Boolean& nodeNameMatches, UInt32& whereaboutsSize, CoTaskMemHandle& whereaboutsBuffer, IResourceManagerShim& resourceManagerShim) +0
System.Transactions.Oletx.DtcTransactionManager.Initialize() +155
System.Transactions.Oletx.DtcTransactionManager.get_ProxyShimFactory() +76
System.Transactions.TransactionInterop.GetOletxTransactionFromTransmitterPropigationToken(Byte[] propagationToken) +160
System.Transactions.TransactionStatePSPEOperation.PSPEPromote(InternalTransaction tx) +78
...[etc...]
我们理解的是,这是因为Azure does not support distributed transactions。
现在,我们尝试使用SqlTransactions:
using(var db1 = new Db1Context())
using(var db2 = new Db2Context())
{
if(db1.Database.Connection.State == ConnectionState.Closed)
{
//transaction can only work on open connection
db1.Database.Connection.Open();
}
using(var tx = db1.Database.Connection.BeginTransaction())
{
//ArgumentException on next line
db1.Users.Single(u => u.Email == oldEmail).Email = someEmail;
db2.Users.Single(u => u.Email == oldEmail).Email = someEmail;
db1.SaveChanges();
db2.SaveChanges(); //what if this fails?
}
}
失败并显示错误:
ArgumentException:“EntityConnection只能使用封闭的DbConnection构建。”
那我们怎么做呢?
答案 0 :(得分:0)
简单地说,你不能。您需要实现2PC才能支持此功能。听起来像Azure有一些非常严重的限制。