问题
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