类似的问题被问到here,但没有答案。
我正在尝试使用带有EF CTP4和SQL CE 4的System.Transactions.CommittableTransaction。
我为ASP.NET MVC Controller操作创建了以下事务属性:
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有关吗?
答案 0 :(得分:2)
我遇到了同样的问题。您不能将事务与CE连接一起使用。我最终让我的datacontext管理我的ce连接并实现一个工作单元模式来保存我的操作,然后在SqlCeTransaction中执行所有调度的操作,然后自己调用commit或rollback。