还有一个类似的问题:here,但没有答案。
我正试图使用一个系统:交易,与EFCTP4和CEQ4的交流。
我为我的协会创造了以下交易归属感。 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();
}
}
}
When I use this filter I get the error:
系统. InvalidOperation 例外: 不能在交易范围内招募联系物体。
然而,以下测试通行证:
[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的初衷有关?