gpt4 book ai didi

c# - 如何在Entity框架中应用事务

转载 作者:行者123 更新时间:2023-12-01 23:31:21 24 4
gpt4 key购买 nike

我有两张 table 。我正在使用 Entity Framework 更新这些表。这是我的代码

public bool UpdateTables()
{
UpdateTable1();
UpdateTable2();
}

如果任何表更新操作失败,则不应提交其他表更新操作,我如何在 Entity Framework 中实现此目的?

最佳答案

using (TransactionScope transaction = new TransactionScope())
{
bool success = false;
try
{
//your code here
UpdateTable1();
UpdateTable2();
transaction.Complete();
success = true;
}
catch (Exception ex)
{
// Handle errors and deadlocks here and retry if needed.
// Allow an UpdateException to pass through and
// retry, otherwise stop the execution.
if (ex.GetType() != typeof(UpdateException))
{
Console.WriteLine("An error occured. "
+ "The operation cannot be retried."
+ ex.Message);
break;
}
}

if (success)
context.AcceptAllChanges();
else
Console.WriteLine("The operation could not be completed");

// Dispose the object context.
context.Dispose();
}

关于c# - 如何在Entity框架中应用事务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6274411/

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