Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Detach an entity and the related entities gone

When I use Entity Framework, I want to query out a record in a context and add it to another context with the same schema, after query out the record, I detach it from the context, but the related entities are all away, is there any way to solve it?

Thanks in advance!

like image 538
James Avatar asked Dec 21 '22 04:12

James


2 Answers

This is "by design". EF can detach entities only one by one but in the same time EF doesn't support object graphs composed of attached and detached entities. Because of that when you detach entity it will break all relations to the rest of attached object graph. Detaching whole object graph is currently not supported but you can vote for this feature on Data UserVoice.

As a workaround you can turn off lazy loading on your context, use eager loading described by @CodeWarrior to load exactly data you need to pass to other context. Once you have data loaded serialize them to stream and immediately deserialize them to the new instance of the object graph. This is the way how to make deep clone of entity graph which is detached but has all relations intact (turning lazy loading off is needed otherwise serialization will load all other navigation properties as well which can result in much bigger object graph then expected). The only requirement is that your entities must be serializable by serializer of your choice (be aware of circular references which usually require some special handling or additional attributes on your entities).

like image 150
Ladislav Mrnka Avatar answered Jan 05 '23 00:01

Ladislav Mrnka


Are you asking how to load the child entities? If so, you can do eager loading with the .Include method. Given a Person class and a PhoneNumber class where Person has a collection of PhoneNumber, you could do the following:

List<Person> People = db.People.Where(p => p.Name = "Henry")
                               .Include("PhoneNumbers")
                               .ToList();

Or you can do what is called explicit loading where you load your entities and call the .Load method on the collections of child and related entities that you want to load. Generally you do this when you do not have LazyLoading enabled (and LazyLoading is enabled by default in 4.0+ don't recall in previous versions).

Regardless of how you query and load them, you will have to detach entities that you want to attach to a different context.

Here is a link to a pretty good MSDN article on loading entities.

like image 34
CodeWarrior Avatar answered Jan 04 '23 22:01

CodeWarrior