简体   繁体   中英

How to delete children records in asp.net via ef

I have to objects in my project, each one represent a table in db. One name is "form" and the other is "forminput", one form object has many forminput objects.

below is my code:

form form = db.forms.find(id);
form.name = "new name";
form.forminputs.clear();
foreach( forminput input in inputs)
{
  form.forminputs.add(input);
}
db.Entry(form).state = EntityState.Modified;
db.SaveChanges();

What I want is delete all children forminput objects, and create a bunch of new forminput objects, and save in db in one call SaveChanges method.

But system tell me can not modify relationship, because one or more key can't be null.

Who can help me ? Thanks.

You need to also remove each object, not only the relationship.

foreach (var input in form.forminputs.ToArray())
{
    db.Entry(input).State = EntityState.Deleted;
}
// form.forminputs.Clear();

or

form.Set<forminput>().RemoveRange(form.forminputs);
// form.forminputs.Clear();

PS

The Clear is not needed, as marking as Deleted or RemoveRange will remove each object from the collection.

And marking the form as Modified is not necessary as it's a tracked entity and it will know any change of the current state.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM