SQL CE 4 System.Transaction support

跟風遠走 提交于 2019-12-12 16:57:21

问题


A similar question was asked here but had no answer.

I am attempting to use a System.Transactions.CommittableTransaction with EF CTP4 and SQL CE 4.

I have created the following transaction attribute for my ASP.NET MVC Controller actions:

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:

System.InvalidOperationException: The connection object can not be enlisted in transaction scope.

However, the following test passes:

    [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);
    }

Has this something to do with how I am initializing the DbContext?


回答1:


I ran into this same issue. You cannot use Transactions with the CE Connection. I ended up having my datacontext manage my ce connection and implementing a unit of work pattern to hold my actions, then executing all the scheduled actions inside a SqlCeTransaction then calling commit or rollback myself.

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



来源:https://stackoverflow.com/questions/4203358/sql-ce-4-system-transaction-support

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!