Question

We have recently decided to use EF6 code first in one of our projects so I am undergoing a paradigm change. I really enjoy EF but some things are so different they seem wrong.

I just want to run a scenario by the community to see if I am thinking correctly.

We have an entity that has child entities of the same type.

If I was saving a child normally I would just save a new entity with the parent id set to the id of the parent. In the entity world they are connected through a navigation property of the same type as follows:

public class SomeType
{
public id;
....

public virtual IList<SomeType> Children
}

Obviously the standard approach doesn't work here since I am not manipulating DB foreign keys manually.

It seems the "Entity Way" would be to first use DBCcontext and linq to select the parent, then add the new entity to the Children list and save the whole thing.

Which is fine and logical - but it just seems a little inefficient to do a select every time i am doing a save.

Am I really missing something here do I just need to get used to a different way of thinking here?

Thank you!

Was it helpful?

Solution

If I'm getting your problem right, then you can and should save the child as a simple Sometype with a parentId, just as you would without using the entity framework. The automagic of the EF shouldn't cause a problem for you here, and you would not be breaking any best practices.

Essentially: If the parent entity is already loaded into context, it's usually best to add the new entity to the collection of navigation properties (Children in your case, but any foreign key). If the parent is not loaded and you know it's id, populate the foreign key field and save it just as you always did.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top