gpt4 book ai didi

c# - 确保 2 个数据库的完整性

转载 作者:行者123 更新时间:2023-11-30 13:00:58 25 4
gpt4 key购买 nike

所以,我有两个数据库...用户数据库和另一个也包含用户表的数据库。两者都有一个电子邮件字段。我想同时更新两个电子邮件字段。

(简化的)代码如下所示:

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 can only be constructed with a closed DbConnection."

那么我们怎样才能做到这一点呢?

最佳答案

简单地说,你不能。您需要实现 2PC 来支持这一点。听起来 Azure 有一些非常严格的限制。

关于c# - 确保 2 个数据库的完整性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21093859/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com