I try to remove the Entity link in a one-to-many relationship as follows, but I get an error when I try to attach an o object to my DbContext. Error:
"Adding a relationship to an entity in the Deleted state is not allowed."
I also tried the following instead of setting the EntityState:
_db.OrganizationMetrics.Remove(om)
What is the correct way to remove this?
<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
UPDATE:
This is my current code. The key is to not display child objects back to the parent entity model from the view model, so that I can deal with them individually.
<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
source
share