【问题标题】:Invoke SaveChanges two times in one transaction在一个事务中调用 SaveChanges 两次
【发布时间】:2013-03-15 04:16:21
【问题描述】:

所有,我是新来的。我的问题是如何在一个事务中调用 savechanges 两次。 以下是我的代码:

var order = new Order();

// modify order's properties

db.orders.add(order);
db.SaveChanges();

db.Entry(order).reload();

// do some other work about the order entity
db.Entry(order).state = EntityState.Modified;
db.SaveChanges();

但是第二次 SaveChanges 失败了。错误信息是“影响了意外的行数 (0)。加载后可能会修改或删除实体。刷新 ObjectStateManager”。

我的问题是如何使第二个 SaveChanges() 工作。因为订单实体中的属性代码是基于数据库中自定义函数的自增自定义字符串字段。

谢谢

【问题讨论】:

  • 如果你没有设置AutoDetectChangesEnabled为false,你不需要手动设置状态

标签: asp.net-mvc entity-framework


【解决方案1】:

您不需要调用 .Reload(),正如@maxlego 提到的,如果您没有将 AutoDetectChangesEnabled 的默认值更改为 true,则不需要将 .State 设置为 modified。

您应该能够遵循此模式并获得所需的结果。您可以在有或没有 TransactionScope 的情况下执行以下操作。使用 TransactionScope 的好处是,如果您对 SaveChanges() 的第二次调用因异常而失败,则第一次调用所做的更改将被回滚。另一方面,如果您希望第一次调用 SaveChanges() 成功,即使第二次调用失败,您应该删除 TransactionScope 代码。

using (var db = new MyContext())
using (var scope = new TransactionScope())
{
    var order = new Order();

    // modify order's properties

    db.orders.add(order);
    db.SaveChanges();

    // make additional changes...
    // E.g. assuming order.ID is an auto-incrementing primary key
    // that is determined by the database I can now use the
    // value the database set to log this change...

    // save changes
    db.SaveChanges();

    // commit the transaction
    scope.Complete();
}

【讨论】:

    猜你喜欢
    • 2012-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-23
    • 2014-09-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多