gpt4 book ai didi

c# - 在 Entity Framework 中使用 2 个 DbContext 回滚事务。使用 TransactionScope 还是 TransactionBegin?

转载 作者:太空狗 更新时间:2023-10-29 20:13:25 25 4
gpt4 key购买 nike

我有 2 个 DbContext',我以一种形式调用它们,如您在此处所见:

    dbcontext1.add(object);
dbcontext1.save();
dbcontext2.add(object);
dbcontext2.save();

所以我有一个问题:如果发生一些问题并且我的记录被保存在 DbContext1 而不是在 DbContext2 中,我需要回滚我的事务。

我搜索并找到了两种方法:使用 BeginTransactionTransactionScope。我对应该使用哪一个以及它们之间的区别是什么感到困惑?

我发现了类似的东西,但我不知道如何回滚:

using (TransactionScope scope = new TransactionScope())  
{
using (EFEntities1 dc = new EFEntities1())
{
dc.USERS.Add(user);
dc.SaveChanges();
}

using (EFEntities2 dc = new EFEntities2())
{
dc.USERS.Add(user);
dc.SaveChanges();
}

scope.complete();
}

最好的问候

最佳答案

I am confused about which one I should use and what the differences between them are?

不同之处在于,TransactionScope 的行为就像一个常规的、轻量级的本地事务,只要您将它用于单个数据库连接 (SQL Server 2005) 或同一数据库上的多个连接 (SQL服务器 2008 及更高版本)。如果在同一事务范围内使用两个或多个连接或访问多个数据库(同样,取决于 SQL Server 版本),则将其提升为分布式事务(因此已向 MSDTC 注册)。在您的情况下,它将得到提升。

I found something like this but i don;'t know how can i roll back this.

只要您不调用Complete,事务范围就会在范围结束时立即回滚(例如处置、使用结束等)。

如果任何一个数据库上下文抛出异常,那么在您的代码中 Complete 将不会被调用,事务将被回滚。

来自 MSDN:

If no exception occurs within the transaction scope (that is, between the initialization of the TransactionScope object and the calling of its Dispose method), then the transaction in which the scope participates is allowed to proceed. If an exception does occur within the transaction scope, the transaction in which it participates will be rolled back.

这也是Rollback方法不存在的原因。

您可能还想查看要使用的隔离级别。默认为 Serializable

关于c# - 在 Entity Framework 中使用 2 个 DbContext 回滚事务。使用 TransactionScope 还是 TransactionBegin?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25461008/

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