【发布时间】:2015-12-08 15:29:56
【问题描述】:
我目前正在使用 TransactionScope 来管理我的数据层中的事务,但我遇到了嵌套事务和异步的问题,即在嵌套事务期间连接似乎关闭或事务被提升为 MSDTC。我还没有找到确切的问题,但在阅读之后,看起来这种情况不支持particuarly well,我应该改用 Database.BeginTransaction()。
我的问题是我找不到有关 Database.BeginTransaction() 如何处理嵌套事务的信息,特别是在我想要使用环境事务而不是创建新事务的情况下。我的怀疑是它不打算以这种方式工作,如果我想管理嵌套事务,我应该抽象出事务管理以给予我更多控制权。
不想添加不必要的抽象层我想知道是否有人在这方面有经验并且可以确认 Database.BeginTransaction() 嵌套在另一个事务中时的行为?
关于我的 DAL 的其他信息:基于 CQS 模式,我倾向于将与 Db 相关的代码封装在命令或查询处理程序中,因此这个嵌套如何发生的简化/人为示例如下:
public class AddBlogPostHandler
{
private readonly MyDbContext _myDbContext;
public AddBlogPostHandler(MyDbContext myDbContext)
{
_myDbContext = myDbContext;
}
public async Task ExecuteAsync(AddBlogPostCommand command)
{
using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
{
// .. code to create and add a draft blog post to the context
await _myDbContext.SaveChangesAsync();
var publishBlogPostCommand = new PublishBlogPostCommand();
// ..set some variables on the PublishBlogPostCommand
await PublishBlogPostAsync(command);
scope.Complete();
}
}
}
public class PublishBlogPostHandler
{
private readonly MyDbContext _myDbContext;
public PublishBlogPostHandler(MyDbContext myDbContext)
{
_myDbContext = myDbContext;
}
public async Task ExecuteAsync(PublishBlogPostCommand command)
{
using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
{
// .. some code to do one set of update
await _myDbContext.SaveChangesAsync();
// .. some other db updates that need to be run separately
await _myDbContext.SaveChangesAsync();
scope.Complete();
}
}
}
【问题讨论】:
标签: c# entity-framework transactions entity-framework-6