2

一個類似的問題被問到here但沒有答案。SQL CE 4 System.Transaction支持

我試圖使用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?

回答

2

我遇到了同樣的問題。您無法使用具有CE連接的交易。我最終讓我的datacontext管理我的ce連接並實現一個工作模式單元來保存我的動作,然後在SqlCeTransaction中執行所有計劃的動作,然後調用commit或rollback自己。

http://msdn.microsoft.com/en-us/library/csz1c3h7.aspx