Entity Framework Disable Entity and Related Objects

When I use the Entity Framework, I want to request a record in the context and add it to another context with the same scheme, after requesting the record, I disconnect it from the context, but the related objects are all away, is there any way to solve it?

Thanks in advance!

+4
source share
2 answers

This is "by design." EF can only separate objects one after another, but at the same time, EF does not support graphic objects consisting of attached and separate objects. Because of this, when you detach an object, it breaks all the relationships into the rest of the bound graph of the objects. Separating the entire graph of an object is not yet supported, but you can vote for this Data UserVoice feature .

As a workaround, you can disable lazy loading in your context, use the loadable download described by @CodeWarrior to load exactly the data that needs to be transferred to another context. After loading the data, serialize it into a stream and immediately deserialize it into a new instance of the object graph. This is a way to make a deep cloned entity graph that is disconnected but has all relationships intact (debugging with lazy loading is required, otherwise serialization will load all other navigation properties, which can lead to the expectation of a much larger graph of objects). The only requirement is that your objects must be serializable using the serializer of your choice (remember about circular references, which usually require some special processing or additional attributes on your entities).

+8
source

Are you asking how to load child objects? If so, you can download using the .Include method. Given the Person class and the PhoneNumber class, where Person has a PhoneNumber collection, you can 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 objects, and call the .Load method for collections of child and related objects that you want to load. Typically, you do this when you don’t have LazyLoading (and LazyLoading is enabled by default in 4.0+, I don’t remember in previous versions).

No matter how you request and load them, you will have to detach the objects that you want to add to another context.

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

+3
source

Source: https://habr.com/ru/post/1386231/


All Articles