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
"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:
child.Parent = parentObject
. The parent object should be fetched from the database first.parentObject.Children.Add(child)
. Also requires a pre-existing parent object from the database.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
.