title: Adding a relationship with an entity which is in the Deleted state is not allowed
body: <p>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:</p>
  
  <p>"Adding a relationship with an entity which is in the Deleted state is not allowed."</p>
  
  <p>I have also tried the following in place of setting the EntityState:</p>
  
  <pre><code> _db.OrganizationMetrics.Remove(om)
  </code></pre>
  
  <p>What is the right way to remove this?</p>
  
  <pre><code>&lt;HttpPost()&gt;
  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
  </code></pre>
  
  <p>UPDATE:</p>
  
  <p>This is my now functioning code.  The key is to <strong>not</strong> map the children entities back to the parent entity model from the view model, so that I can deal with them individually.</p>
  
  <pre><code>    &lt;HttpPost()&gt;
      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
  </code></pre>