Entity Framework - Add Child Entity

点点圈 提交于 2019-12-29 06:46:10

问题


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


回答1:


"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.



来源:https://stackoverflow.com/questions/13148585/entity-framework-add-child-entity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!