Quantcast
Channel: ADO.NET, Entity Framework, LINQ to SQL, NHibernate
Viewing all articles
Browse latest Browse all 1698

How to delete child from children collection of parent in EF core? (removing an orphan?)

$
0
0

I have a parent table and an associated child table in a one-to-many relationship.  I need a solution for deleting specific items from the child table when modifying the collection of the parent.  Example table/models:

public class Parent
{
  public int ParentId
  public string Field1
  public string Field2

  public virtual List<Child> Children
}

public class Child
{
  public int ChildId
  public string Prop1
  public string Prop2
  public string Prop3
  public int ParentID

  public virtual Parent Parent
}

So when I edit a Parent object, it lists all associated Children.  I can then mark specific children that I want removed, and POST back the Parent object with the children I want to keep.  This is where I haven't had luck in getting the marked-children to be removed.

[HttpPost]
public async Task<IActionResult> Edit(Parent model)
{
  if (ModelState.isValid)
  {
    _context.Update(model); // using breakpoint I can see that only the children I want are left in the object
    await _context.SaveChangesAysnc();
  }

  // return a View here
}

However, going to my table, this doesn't remove the marked children.  So what do I need to do?


Viewing all articles
Browse latest Browse all 1698

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>