拆卸新对象后重新导航属性 [英] Reloading navigation properties after detaching a new object

查看:102
本文介绍了拆卸新对象后重新导航属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用具有POCO对象的实体框架,并具有以下场景:



我创建一个新的父对象并向其添加一个子对象。然后我保存更改并分离父对象。在这个时候,它的孩子收藏空白。

  parent = new Parent(){label =Test}; 
parent.Children.Add(new Child(){label =Test});
context.Parents.AddObject(parent);
context.SaveChanges();
context.Detach(parent);

当我将父对象重新连接到其他上下文时,我必须显式加载相应的属性才能访问儿童系列。

  context.Parents.Attach(parent); 
context.LoadProperty(parent,p => p.Children);

导航属性是否有任何方式延迟加载,而不必手动加载每个加载?



如果不是创建一个新对象,我检索一个现有对象,不会发生问题:分离时,children集合为空;但是在重新安装后,孩子们会自动懒惰加载。

解决方案

而不是:

  parent = new Parent(){label =Test}; 

尝试使用:

  parent = context.CreateObject< Parent>(); 
parent.label =Test;


I am using Entity Framework with POCO objects and have the following scenario:

I create a new parent object and add a child object to it. Then I save changes and detach the parent object. At this moment its children collection gets empty.

parent = new Parent() { label = "Test" };
parent.Children.Add(new Child() { label = "Test" });
context.Parents.AddObject(parent);
context.SaveChanges();
context.Detach(parent);

When I reattach the parent object to a different context, I have to explicitly load the corresponding property to access the children collection.

context.Parents.Attach(parent);
context.LoadProperty(parent, p => p.Children);

Is there any way for the navigation properties to lazy load instead of having to load manually every one of them?

If instead of creating a new object, I retrieve an existing object, the problem does not occur: the children collection gets empty when detached; but after reattaching, the children are lazy loaded automatically.

解决方案

Instead of:

parent = new Parent() { label = "Test" };

Try to use:

parent = context.CreateObject<Parent>();
parent.label = "Test";

这篇关于拆卸新对象后重新导航属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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