我正在尝试以以下方式删除对一对多关系中实体的引用,但是当我尝试将对象“o”附加到我的 DbContext 时收到错误消息。错误是:
“不允许添加与处于已删除状态的实体的关系。”
我还尝试了以下方法来代替设置 EntityState:
_db.OrganizationMetrics.Remove(om)
删除它的正确方法是什么?
<HttpPost()>
Function Edit(ByVal ovm As OrganizationViewModel)
Dim o As Organization
o = AutoMapper.Mapper.Map(Of OrganizationViewModel, Organization)(ovm)
For Each om In o.OrganizationMetrics
_db.OrganizationMetrics.Attach(om)
If om.Value = "removeMe" Then
_db.Entry(om).State = EntityState.Deleted
ElseIf om.Id = 0 Then
_db.Entry(om).State = EntityState.Added
Else
_db.Entry(om).State = EntityState.Modified
End If
Next
_db.Organizations.Attach(o) 'Error is thrown here
If (ModelState.IsValid) Then
_db.Entry(o).State = EntityState.Modified
_db.SaveChanges()
Return RedirectToAction("Index")
Else
Return View(ovm)
End If
End Function
更新:
这是我现在运行的代码。关键是不要将子实体从视图模型映射回父实体模型,以便我可以单独处理它们。
<HttpPost()>
Function Edit(ByVal ovm As OrganizationViewModel)
Dim o As Organization
o = AutoMapper.Mapper.Map(Of OrganizationViewModel, Organization)(ovm) //The Automapper code ignores the OrganizationMetrics members
_db.Organizations.Attach(o)
For Each om In ovm.OrganizationMetrics
_db.OrganizationMetrics.Attach(om)
If om.Value = "removeMe" Then
_db.Entry(om).State = EntityState.Deleted
ElseIf om.Id = 0 Then
_db.Entry(om).State = EntityState.Added
Else
_db.Entry(om).State = EntityState.Modified
End If
Next
If (ModelState.IsValid) Then
_db.Entry(o).State = EntityState.Modified
_db.SaveChanges()
Return RedirectToAction("Index")
Else
Return View(ovm)
End If
End Function