我试图以下列方式删除对一对多关系中的实体的引用,但是当我尝试将对象“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
答案 0 :(得分:3)
当您使用_db.Organizations.Attach(o)
附加o时,它会遍历所有子项并发现其中一些被删除。当它试图附加它们时,您会收到您正在显示的错误。这很有道理。
退后一步,弄清楚你想做什么。删除内容的最简单方法是获取它然后删除它。类似的东西:
context.DeleteObject(context.MyEntity.Single(r => r.Id == myId));
如果需要,可以只使用其键来模拟MyEntity
对象,然后删除该对象,它也会起作用并保存一个选择查询。