简体   繁体   English

使用实体框架的乐观并发更新

[英]Optimistic concurrency updates using Entity Framework

I have a repository using EF 4.1 and DbContext when updating an object I receive this error 更新对象时,我有使用EF 4.1和DbContext的存储库我收到此错误

Store update, insert, or delete statement affected an unexpected number of rows (0). 存储更新,插入或删除语句影响了意外的行数(0)。 Entities may have been modified or deleted since entities were loaded. 自加载实体以来,实体可能已被修改或删除。 Refresh ObjectStateManager entries. 刷新ObjectStateManager条目。

I suppose is connected with optimistic concurrency updates.. Any idea how to solve it? 我想是与乐观的并发更新相关的。任何想法如何解决?

  public void UpdateAddingCandidate(Event eventObj, int candidateId)
    {
        Candidate newCandidate = db.Candidates.AsNoTracking().FirstOrDefault(x => x.CandidateId == candidateId);
        eventObj.Candidate = newCandidate;
        eventObj.CandidateId = newCandidate.CandidateId;
        db.Entry(eventObj).State = EntityState.Modified;
    }

Look into ObjectContext.Refresh, which allows you to refresh entities from the database. 查看ObjectContext.Refresh,它使您可以从数据库中刷新实体。 You can set the RefreshMode to ClientWins or StoreWins. 您可以将RefreshMode设置为ClientWins或StoreWins。

Use Try...Catch logic and handle the conflict in the catch to force the change with ClientWins or pull down the changed data into the context and restart the edit. 使用Try ... Catch逻辑并处理catch中的冲突,以使用ClientWins强制进行更改,或将更改的数据拉入上下文并重新开始编辑。 In most cases, the latter is the better approach. 在大多数情况下,后者是更好的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM