实体框架SaveChanges()不更新数据库 [英] Entity Framework SaveChanges() not updating the database

查看:115
本文介绍了实体框架SaveChanges()不更新数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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未能跟踪对象之类的问题,但没有发生此类错误的情况,我会期望失败。

is called winningBid is updated as expected but paymentAttempt isn't. Why is this? It is really frustrating. There is no error either. I would expect a failure to occur if there was a problem like EF wasn't tracking the object or something like that, but no such error is happening.

推荐答案

这是因为您需要将 paymentAttempt 对象传递给上下文,以使其知道它是需要更新的对象。

That's because you need to pass the paymentAttempt object to your context, to let it know that it is an object that needs to be updated.

例如,假设 _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);

这篇关于实体框架SaveChanges()不更新数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆