实体框架分离实体和相关实体 [英] Entity Framework Detach an entity and the related entities gone

查看:109
本文介绍了实体框架分离实体和相关实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用Entity Framework时,我想在上下文中查询一条记录,并将其添加到具有相同模式的另一个上下文中,在查询出记录之后,将其从上下文中分离出来,有没有办法解决?

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?

提前感谢!

推荐答案

这是按设计。 EF可以逐个分离实体,但同时EF不支持由附加和分离的实体组成的对象图。因为这样,当你分离实体时,它会将所有的关系破坏到附加的对象图的其余部分。目前不支持分离整个对象图,但您可以在 Data UserVoice

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.

作为解决方法,您可以关闭延迟加载上下文中,使用@CodeWarrior描述的加载加载要准确传递给其他上下文的数据。一旦你把数据加载到序列化它们,然后立即将它们反序列化到对象图的新实例。这是如何使分离的实体图的深度克隆,但是具有完全关系的所有关系(如果需要延迟加载,否则序列化将加载所有其他导航属性,这可以导致更大的对象图,并且预期)。唯一的要求是您的实体必须通过您选择的序列化程序进行序列化(请注意通常需要一些特殊处理或其他属性的循环引用)。

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

这篇关于实体框架分离实体和相关实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆