Asp.net mvc MVC 4-ObjectStateManager中已存在具有相同键的对象

Asp.net mvc MVC 4-ObjectStateManager中已存在具有相同键的对象,asp.net-mvc,vb.net,entity-framework,asp.net-mvc-4,Asp.net Mvc,Vb.net,Entity Framework,Asp.net Mvc 4,首先,道歉。我知道这方面有很多问题,但我已经搜索了几天,找不到任何解决方案,我可以调整到我的情况(或太无聊了,无法调整) 从本质上说,这就是我试图实现的目标:显示的代码用于将编辑保存到特定类中的一个项——该功能运行良好。然后,基于该条目的Order属性,我想更改数据库中其他项的Order属性。这些更改在For Each语句中进行 正在EntityState.Modified上引发代码中显示的错误。我知道错误可能是由于For Each语句导致的,因为db项基本上被调用了两次;但是,我不确定如何修复

首先,道歉。我知道这方面有很多问题,但我已经搜索了几天,找不到任何解决方案,我可以调整到我的情况(或太无聊了,无法调整)

从本质上说,这就是我试图实现的目标:显示的代码用于将编辑保存到特定类中的一个项——该功能运行良好。然后,基于该条目的Order属性,我想更改数据库中其他项的Order属性。这些更改在For Each语句中进行

正在EntityState.Modified上引发代码中显示的错误。我知道错误可能是由于For Each语句导致的,因为db项基本上被调用了两次;但是,我不确定如何修复它。请帮忙。谢谢大家!

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)
函数编辑(ByVal checklistitem作为checklistitem)作为ActionResult
对于每x个db.项目

如果checklistitem.Order您的数据库不是每个请求的实例?
当您显示编辑表单时,它必须从db中读取checklistitem,因此它将附加到db上下文。
当post时,mvc会创建一个新的相同的键obj,因此它会导致此错误。

如果已经在For循环中更改对象,那么实际需要在If块内设置状态吗?