保存实体更改时出错:ObjectStateManager中已存在具有相同键的对象

时间:2013-04-19 15:36:12

标签: asp.net-mvc entity-framework asp.net-mvc-4

每当我尝试运行以下代码时,我总是会收到此错误:

  

ObjectStateManager中已存在具有相同键的对象。   ObjectStateManager无法跟踪具有相同对象的多个对象   键。

这是我的代码

// find assessmentcase that needs to be updated
var CaseToBeUpdated = db.AssessmentCases
                     .Where(c => c.CaseSeq == score.CaseSeq)
                     .FirstOrDefault();

// create new assessmentcase with updated data                    
AssessmentCase assessmentcase = new AssessmentCase
                                {
                                    CaseSeq = CaseToBeUpdated.CaseSeq,
                                    DateClosed = System.DateTime.Now,
                                    SeqClosedBy = SeqClosedBy,
                                    UserIdClosed = User.Identity.Name,
                                };

// save changes to assessment case table
db.Entry(assessmentcase).State = EntityState.Modified;
db.SaveChanges();

基本上,我正在尝试更新assessmentcase表中的一些数据。我做错了什么?

2 个答案:

答案 0 :(得分:4)

在第一行,您将实体加载到内存,以便EF开始跟踪它。然后你创建另一个具有相同CaseSeq的实体(我相信它是一个主键),然后你尝试将它附加到EF。所以你有2个具有相同主键的实体。不要创建新对象。使用从内存中加载的那个。

// find assessmentcase that needs to be updated
var CaseToBeUpdated = db.AssessmentCases
                     .Where(c => c.CaseSeq == score.CaseSeq)
                     .FirstOrDefault();

CaseToBeUpdated.DateClosed = System.DateTime.Now;
CaseToBeUpdated.SeqClosedBy = SeqClosedBy;
CaseToBeUpdated.UserIdClosed = User.Identity.Name;

// save changes to assessment case table
db.Entry(CaseToBeUpdated).State = EntityState.Modified;
db.SaveChanges();

答案 1 :(得分:2)

为什么不简单地更新检索到的记录?

var CaseToBeUpdated = db.AssessmentCases
                 .Where(c => c.CaseSeq == score.CaseSeq)
                 .FirstOrDefault();

// create new assessmentcase with updated data                    
CaseToBeUpdated.DateClosed = System.DateTime.Now;
CaseToBeUpdated.SeqClosedBy = SeqClosedBy;
CaseToBeUpdated.UserIdClosed = User.Identity.Name;

// this should not be necessary ...   
db.Entry(CaseToBeUpdated).State = EntityState.Modified;
// save changes to assessment case table
db.SaveChanges();