在这里提出了类似的问题,但没有答案。
我正在尝试将 System.Transactions.CommittableTransaction 与 EF CTP4 和 SQL CE 4 一起使用。
我为我的 ASP.NET MVC 控制器操作创建了以下事务属性:
public class TransactionAttribute : ActionFilterAttribute
{
CommittableTransaction transaction;
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
transaction = new CommittableTransaction();
Transaction.Current = transaction;
base.OnActionExecuting(filterContext);
}
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
base.OnResultExecuted(filterContext);
try
{
var isValid = filterContext.Exception == null || filterContext.ExceptionHandled;
if (filterContext.Controller.ViewData.ModelState.IsValid && isValid) {
transaction.Commit();
} else {
transaction.Rollback();
Transaction.Current = null;
}
}
finally
{
transaction.Dispose();
}
}
}
当我使用这个过滤器时,我得到了错误:
System.InvalidOperationException:无法在事务范围内登记连接对象。
但是,以下测试通过:
[Test]
public void Transaction_rolls_back_if_exception()
{
var transaction = new CommittableTransaction();
Transaction.Current = transaction;
try
{
var project = new Project { Title = "Test" };
projectRepo.SaveOrUpdate(project);
context.SaveChanges();
var post = new Post { Title = "Some post" };
blogRepo.SaveOrUpdate(post);
throw new Exception();
context.SaveChanges();
transaction.Commit();
}
catch (Exception ex)
{
transaction.Rollback();
Transaction.Current = null;
}
projectRepo.GetAll().Count().ShouldEqual(0);
blogRepo.GetAll().Count().ShouldEqual(0);
}
这与我初始化 DbContext 的方式有关吗?