【问题标题】:Many update statements in one Transaction in Entity Framework实体框架中的一个事务中的许多更新语句
【发布时间】:2012-07-02 07:19:18
【问题描述】:

我需要更新多个更新语句,但所有更新语句都应该适用于自动性,即更新全部或不更新。

在互联网和其他一些 SO Questions 中,我找到了如何使用 Transaction,但我没有发现其中任何一个说要在一个事务中更新多个语句。 见下面三个更新语句,目前没有在事务下运行

/// this are my update calls.
var report = reportRepository.Update(reportModel);
var book = bookRepository.Update(bookModel);
var mobile = mobileRepository.Update(mobileModel);

// each Update method for all repository will looks like
public returnModel Update(someModel model)
{
    // assign values from model to entity
    Context.ObjectStateManager.ChangeObjectState(entity,System.Data.EntityState.Modified)
    Context.SaveChanges();
}

【问题讨论】:

    标签: asp.net-mvc-3 c#-4.0 entity-framework-4.1


    【解决方案1】:

    您可以将更新包装在TransactionScope

    using (TransactionScope transaction = new TransactionScope())
    {
        var report = reportRepository.Update(reportModel);
        var book = bookRepository.Update(bookModel);
        var mobile = mobileRepository.Update(mobileModel);
        ...
        transaction.Complete();
    }
    

    【讨论】:

      【解决方案2】:

      正如 Darin 提到的,使用事务范围或我的首选方法是让您的存储库属于 IUnitOfWork 接口。调用 update 只是将状态设置为已修改,并且 SaveChanges 发生在您的存储库之外以一次保存所有更改。 这应该在一个事务中自动发生。

      因此,您调用所有更新,然后调用 unitOfWork.SaveChanges,其中您的自定义工作单元类包含对您的上下文的引用并实现在 IUnitOfWork 中定义的称为 Save() 的方法

      【讨论】:

      • 谢谢,你说的是 100% 正确,但在我目前的实现中,这不适合。
      【解决方案3】:

      基本上你需要通过 TransactionScope 类来管理它,使用它你可以对一个模型设置多个更新,然后使用 Transaction.Complete 将你的东西保存在一个事务中。

      详情请查看Updating multiple objects in single transaction in entity framework

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-10-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-10
        • 2018-12-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多