簡體   English   中英

實體框架 SaveChanges() 不更新數據庫

[英]Entity Framework SaveChanges() not updating the database

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是的一個實例DbContext

// 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

我知道這已經晚了,但還有另一種解釋值得一提。 即使您的字段名稱包含 ID 並且可能設置為自動增量,請務必確認您在表中將其聲明為主鍵。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM