entity frameworkSaveChanges()不更新数据库
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一样没有跟踪对象或类似的问题,我会发现无法发生,但是没有发生这样的错误。
那是因为你需要将paymentAttempt
对象传递给你的上下文,让它知道它是一个需要更新的对象。
例如,假设_auctionContext
是_auctionContext
的一个实例:
// 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
尝试添加:
using System.Data.Entity.Infrastructure; using System.Data.Entity;
然后你可以简单地使用:
_auctionContext.Entry(paymentAttempt).State = EntityState.Modified; _auctionContext.SaveChanges();
我对这个问题很感兴趣,但是遇到了另一个问题。 我发现如果你在一个尚未修改的对象上调用SaveChanges(),EF将不会更新任何内容。 这是有道理的,但我需要更新数据库,以便其他用户可以看到已执行SaveChanges(),无论是否有任何字段已更改。 要在不更改任何字段的情况下强制更新:
Dim entry As DbEntityEntry = entities.Entry(myentity) entry.State = Entity.EntityState.Modified