有人问了类似的问题here https://stackoverflow.com/questions/3401796/does-sql-ce-4-ctp-support-ambient-transactions-using-system-transaction-namespa但没有得到答复。
我正在尝试将 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 的方式有关吗?
我遇到了同样的问题。您不能将事务与 CE 连接一起使用。我最终让我的数据上下文管理我的 ce 连接并实现一个工作单元模式来保存我的操作,然后执行 SqlCeTransaction 内的所有计划操作,然后自己调用提交或回滚。
http://msdn.microsoft.com/en-us/library/csz1c3h7.aspx http://msdn.microsoft.com/en-us/library/csz1c3h7.aspx
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)