Entity Framework - Add Child Entity

entity-framework parent-child


Entity Framework 5.0 Code first with existing database. Reverse engineered the classes with power tools. Everything is working great. Database has two tables. One parent and one child with foreign key back to parent ID. ID's are all int with auto increment. I've added a number of parent records and now want to add child records to specific parents. The only way I can see to do this is find the appropriate parent ID by searching the Parents table for a name or some other property and return the ID. Then use that ID in the foreign key property when adding the child. I don't want to crate a new parent so is this the only way to add a child to an existing parent? All of the internet examples seem to add a child along with adding a new parent and not add a child to an existing parent. Any help would be greatly appreciated

10/30/2012 10:36:53 PM

Accepted Answer

"Julie" (Lerman) happens to be one of our teachers when it comes to EF. As she explains in her book DbContext there can be three properties involved in a parent-child association, two navigation properties (parent.Children, child.Parent) and a foreign key property (child.ParentId). You can set one of these or any combination of them in your code.

When EF is triggered to detect changes (e.g. when SaveChanges is invoked) it starts a process called relationship fixup that ensures that the three properties will be in sync.

So you've got three options to add a child entity to a parent:

  1. child.Parent = parentObject. The parent object should be fetched from the database first.
  2. parentObject.Children.Add(child). Also requires a pre-existing parent object from the database.
  3. child.ParentId = parentId, for which you only need to know the id. You can get the Id the way you suggested but just as well, for objects that you know will not be deleted, you can have it saved in some variable to reuse it across transactions.

With the first two options the child object does not need to be added to the context manually. EF knows enough to see that it's new. With the third option it does have to be added to context.Children before SaveChanges.

10/31/2012 8:40:25 AM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow