【问题标题】:SQL CE 4 System.Transaction supportSQL CE 4 System.Transaction 支持
【发布时间】:2010-11-17 10:12:21
【问题描述】:

here 提出了类似的问题,但没有答案。

我正在尝试将 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 的方式有关吗?

【问题讨论】:

    标签: entity-framework-4 sql-server-ce system.transactions ctp4


    【解决方案1】:

    我遇到了同样的问题。您不能将事务与 CE 连接一起使用。我最终让我的数据上下文管理我的 ce 连接并实现一个工作单元模式来保存我的操作,然后在 SqlCeTransaction 中执行所有计划的操作,然后自己调用提交或回滚。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多