gpt4 book ai didi

c# - 忽略特定查询的 TransactionScope

转载 作者:IT王子 更新时间:2023-10-29 04:19:02 26 4
gpt4 key购买 nike

我正在寻找一种在 TransactionScope 处于事件状态时执行查询的方法,并忽略 TransactionScope - 基本上,无论如何我都想执行这个特定的查询。

我正在使用 EF 代码优先,应用程序的设计方式是,在一次调用中多次打开新的数据上下文,每次都有自己的更改,所有这些都包含在单个 TransactionScope 中,假设没有失败,它在最后调用了 Complete()。在上下文中,我们覆盖了 SaveChanges,这样如果 base.SaveChanges() 发生任何异常,我们可以在回滚事务之前捕获它并记录到数据库.

由于 SaveChanges 发生在事务内部,日志记录显然不会发生,因为它与原始调用属于同一事务。我试图完全忽略 TransactionScope 只是为了记录代码。

这是一些精简代码:

// From the context
public override int SaveChanges() {
try {
return base.SaveChanges();
} catch (Exception ex) {

// Writes to the log table - I want this to run no matter what
LogRepo.Log(/*stuff to log from the context*/);

throw;
}
}

// Inside the business logic
public void DoSomething() {
try {
using (var scope = new TransactionScope()) {

using (var context = new FooContext()) {
// Do something
context.SaveChanges();
}
using (var context = new FooContext()) {
// Do something else
context.SaveChanges();
}

scope.Complete();
}
} catch (Exception ex) {
// scope.Complete is never called, so the transaction is rolled back
}
}

我尝试使用常规 ADO.NET 而不是 EF 进行日志记录,但结果仍然相同 - 它也会回滚。

我需要在 SaveChanges 内部进行错误处理,因为我正在记录的是正在保存的实体的状态 - 所以我不能轻易地将日志记录移到其他地方.我可以在 SaveChanges catch 中构建消息,然后将其抛出并让 DoSomething catch 记录它,但是有许多 DoSomething 方法,我宁愿只在一个地方处理这个问题。

最佳答案

如果您在启用抑制选项的情况下将日志调用包装在另一个事务范围内,则不会使用事务范围。

public override int SaveChanges() {
try {
return base.SaveChanges();
} catch (Exception ex) {
using (var scope = new TransactionScope(TransactionScopeOption.Suppress)) {
LogRepo.Log(message); // stuff to log from the context
}

throw;
}
}

关于c# - 忽略特定查询的 TransactionScope,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18257122/

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