在分离的 POCO 代理上设置相关实体 ID
我有一个来自 EF 4.0 的分离的 POCO 代理(分离意味着 ObjectContext 已释放)。
我有一个属性 MyRelatedEntityId,它是导航属性 MyRelatedEntity 的 FK。
碰巧,我知道要为 MyRelatedEntityId 设置什么值,因此我尝试手动设置它......但是分离的 POCO 代理会引发 ObjectContext 已处理的异常。
我该如何做到这一点或者有解决方法吗?
I have a detached POCO proxy from EF 4.0 (detached meaning the ObjectContext has disposed).
I have a property MyRelatedEntityId which is a FK for the navigation property MyRelatedEntity.
As it happens, I know what value I want to set for MyRelatedEntityId, so I try to set it manually....but the detached POCO proxy throws an exception that the ObjectContext has already disposed.
How can I do this or is there a workaround for this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您必须关闭延迟加载。我认为一旦设置了 FK 属性,动态代理将尝试加载相关实体,但由于已处理的上下文而失败。
编辑:
我刚刚检查了这个问题,因为正如您提到的,不应触发延迟加载。问题是自动生成的代码使用 Fixup 方法来设置双向关系。如果您加载了先前的相关实体并更改了 FK,则会将相关实体设置为 null。这会触发修复方法,该方法尝试从先前相关实体的子实体中删除当前实体。如果您在处置上下文之前没有加载它们,您将收到异常。只需尝试调试代码,包括生成的代码。
解决方案是:
You must turn off lazy loading. I think once you set FK property, dynamic proxy will try to load related entity and it fails because of disposed context.
Edit:
I just checked this problem because as you mentioned lazy loading should not be triggered. The problem is autogenerated code which uses Fixup methods to set up a bidirectional relation. If you loaded previous related entity and you change FK it sets related entity to null. This triggers the fixup method which tries to remove the current entity from the previous related entity's childs. If you didn't load them before disposing context you will get an exception. Just try to debug the code including generated one.
The solution is either:
您是否在释放 ObjectContext 之前分离了该实体?您是否尝试在将实体附加到新的 ObjectContext 后设置它?
Did you detatch the entity before the ObjectContext was disposed? Have you tried setting it after attaching the entity to a new ObjectContext?