I am trying to remove a reference to an Entity in a One-To-Many relationship in the following manner, but am receiving an error when I try to attach the object ‘o’ to my DbContext. The error is:
“Adding a relationship with an entity which is in the Deleted state is not allowed.”
I have also tried the following in place of setting the EntityState:
_db.OrganizationMetrics.Remove(om)
What is the right 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 now functioning code. The key is to not map the children entities 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
When you attach o with
_db.Organizations.Attach(o), it goes through all its children and finds that some of them are deleted. When it tries to attach them, you get the error you’re showing. It makes perfect sense.Step back and figure out what it is you want to do. The easiest way to delete something is to get it and then delete it. Something like:
If you want, you can mock the
MyEntityobject with just its key and then delete that object, it will work as well and save you a select query.