【问题标题】:Entity Framework SaveChanges() not updating the database实体框架 SaveChanges() 不更新数据库
【发布时间】:2013-02-13 16:09:12
【问题描述】:
var paymentAttempt = _auctionContext.PaymentAttempts.Where(o => o.Id == paymentAttemptId).SingleOrDefault();
if (paymentAttempt != null)
{
    paymentAttempt.PaymentAttemptStatusId = (int)PaymentAttemptStatus.Defunct;
    paymentAttempt.PaymentAttemptStatus = _auctionContext.PaymentAttemptStatuses.Where(pas => pas.Id == paymentAttempt.PaymentAttemptStatusId).First();

    var relevantWinningBidsTotalPrices = _auctionContext.GetWinningBidsTotalPricesForPaymentAttempt(paymentAttemptId).ToArray();

    foreach (var winningBid in relevantWinningBidsTotalPrices)
    {
        winningBid.Locked = false;
        _auctionContext.UpdateObject(winningBid);
    }
    _auctionContext.SaveChanges();
}

在上面的代码之后

_auctionContext.SaveChanges();

被称为winningBid 会按预期更新,但paymentAttempt 不会。为什么是这样?这真的很令人沮丧。也没有错误。如果出现 EF 没有跟踪对象或类似的问题,我预计会发生故障,但没有发生此类错误。

【问题讨论】:

  • 使用 Attach 将修改后的实体放入上下文中。保存之前。上下文不知道你在说什么。

标签: c# entity-framework


【解决方案1】:

那是因为你需要将paymentAttempt 对象传递给你的上下文,让它知道它是一个需要更新的对象。

例如,假设_auctionContextDbContext 的一个实例:

// any changes related to the paymentAttempt object 

_auctionContext.Entry(paymentAttempt).State = EntityState.Modified;

foreach (var winningBid in relevantWinningBidsTotalPrices)
{
   winningBid.Locked = false;
   _auctionContext.UpdateObject(winningBid);
}

_auctionContext.SaveChanges();

另一个选项是Attach 方法:

_auctionContext.Attach(paymentAttempt);
_auctionContext.ObjectStateManager.ChangeObjectState(paymentAttempt, System.Data.EntityState.Modified);

【讨论】:

  • 我没有 Entry 方法。
  • 4.我们在 EF 之上使用 WCF 数据服务。
【解决方案2】:

如果您没有Entry,请尝试添加:

using System.Data.Entity.Infrastructure;

using System.Data.Entity;

那么你可以简单地使用:

_auctionContext.Entry(paymentAttempt).State = EntityState.Modified;
_auctionContext.SaveChanges();

【讨论】:

    【解决方案3】:

    我遇到了这个问题,但遇到了不同的问题。我发现,如果您在尚未修改的对象上调用 SaveChanges(),EF 将不会更新任何内容。这是有道理的,但我需要更新数据库,以便其他用户可以看到 SaveChanges() 已执行,无论是否有任何字段已更改。要在不更改任何字段的情况下强制更新:

        Dim entry As DbEntityEntry = entities.Entry(myentity)
        entry.State = Entity.EntityState.Modified
    

    【讨论】:

      【解决方案4】:

      我知道这已经晚了,但还有一个值得一提的解释。即使您的字段名称包含 ID 并且可能设置为自动增量,请务必确认您已在表中将其声明为主键。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-03
        相关资源
        最近更新 更多