[英]MVC 4 - An object with the same key already exists in the ObjectStateManager
First of all - apologies. 首先-道歉。 I know that there are a lot of questions about this but I've been searching for a few days and couldn't find any solutions that I was able to tweak to my situation (or was too dull to tweak). 我知道对此有很多问题,但是我已经搜索了几天,却找不到我可以根据自己的情况进行调整的解决方案(或者太迟钝而无法调整)。
Essentially, this is what I'm trying to accomplish: The code shown is for saving an edit to one item in a particular class --- that functionality works fine. 本质上,这就是我要完成的工作:所示代码用于将编辑内容保存到特定类中的一个项目上-功能正常。 Then, based off the Order property of that entry, I then want to change other items' Order property in the database. 然后,基于该条目的Order属性,然后我想在数据库中更改其他项目的Order属性。 Those changes are made in the For Each statement. 这些更改在For Each语句中进行。
The error shown in the code is being thrown on EntityState.Modified. 代码中显示的错误被抛出在EntityState.Modified上。 I know that the error is probably resulting from the For Each statement due to the db items basically being called upon twice; 我知道错误可能是由于For Each语句引起的,这是因为db项基本上被调用了两次; however, I'm unsure of how to fix it. 但是,我不确定如何修复它。 Please help. 请帮忙。 Thank you! 谢谢!
Function Edit(<Bind(Include:="ID,Column,Order,Type,Header,Expandable,Expansion,Instruction")> ByVal checklistitem As ChecklistItem) As ActionResult
For Each x In db.Items
If checklistitem.Order <= x.Order And checklistitem.Type = x.Type And checklistitem.ID <> x.ID Then
x.Order += 1
End If
Next
If ModelState.IsValid Then
db.Entry(checklistitem).State = EntityState.Modified 'ERROR RETURNED ON THIS LINE: An object with the same key already exists in the ObjectStateManager. The existing object is in the Modified state. An object can only be added to the ObjectStateManager again if it is in the added state.'
db.SaveChanges()
Return RedirectToAction("Index")
End If
Return View(checklistitem)
your db is not instance per request? 您的数据库不是每个请求的实例?
when you show you edit form,it must read checklistitem from db ,so it will attach to db context. 当您显示要编辑的表单时,它必须从db读取checklistitem,因此它将附加到db上下文。
and when post,a new same key obj create by mvc,so it make this err. 并且在发布时,由mvc创建了一个新的相同键obj,因此使它出错。
2 obj with same key,what attach to 1 context 2个具有相同键的obj,附加到1个上下文
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.