实体框架SaveChanges()不更新数据库

Sac*_*nth 9 c# entity-framework

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();
}
Run Code Online (Sandbox Code Playgroud)

在上面的代码之后

_auctionContext.SaveChanges();
Run Code Online (Sandbox Code Playgroud)

调用winningBid按预期更新但paymentAttempt不是.为什么是这样?真的很令人沮丧.也没有错误.如果像EF一样没有跟踪对象或类似的问题,我会发现无法发生,但是没有发生这样的错误.

Jor*_*rge 16

那是因为你需要将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();
Run Code Online (Sandbox Code Playgroud)

另一种选择是Attach方法:

_auctionContext.Attach(paymentAttempt);
_auctionContext.ObjectStateManager.ChangeObjectState(paymentAttempt, System.Data.EntityState.Modified);
Run Code Online (Sandbox Code Playgroud)


小智 5

如果您没有Entry尝试添加:

using System.Data.Entity.Infrastructure;

using System.Data.Entity;
Run Code Online (Sandbox Code Playgroud)

那么你可以简单地使用:

_auctionContext.Entry(paymentAttempt).State = EntityState.Modified;
_auctionContext.SaveChanges();
Run Code Online (Sandbox Code Playgroud)