user2155362
user2155362

Reputation: 1703

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.

Upvotes: 4

Views: 350

Answers (1)

Yuliam Chandra
Yuliam Chandra

Reputation: 14640

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.

Upvotes: 2

Related Questions