Shawn Mclean
Shawn Mclean

Reputation: 57469

Entity framework update children when updating parent

I'm sending both parent and its children to be updated to my service layer.

The model is set up as follows:

public class Parent
{
    public int ParentId { get; set; }
    public ICollection<Child> Children;
}

public class Child
{
    public int ChildID {get; set;}
    public virtual Parent Parent{get;set}
    public virtual int ParentId{get; set;}
    public string FirstName { get; set; }
}

The behaviour I'd like is that the children are always attached to the parent, so if a child is in the database that is not found attached, we should remove it. If it does not exist, create it. If it exist, update it.

How do I accomplish this without writing code to make all these calls manually? Like remove all, then re-add all.

Upvotes: 1

Views: 6670

Answers (1)

Slauma
Slauma

Reputation: 177133

You don't need to remove all children and re-add them (which can be a problem anyway if you have for example other entities in the database which refer to one of the children you only want to update. Deleting and re-adding it would lead to a foreign key constraint violation).

What you actually need to do is more complicated :(

You must load the original object graph in the database and then check child by child if it has been deleted, if it is new or if it already exists.

An example which fits quite exactly to your model is here:

The relationship could not be changed because one or more of the foreign-key properties is non-nullable

Entity Framework doesn't support you to update an object graph in the database with a detached object graph. The only support it offers is updating scalar and complex properties. For those you can use ApplyCurrentChanges (for ObjectContext) or Entry(entity).CurrentValues.SetValues (for DbContext). The latter is used in the linked example to update the parent`s and each child's scalar properties. But updating relationships between entities is a manual task.

Upvotes: 2

Related Questions