Reloading navigation properties after detaching a new object

≡放荡痞女 提交于 2019-12-24 05:52:58

问题


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.


回答1:


Instead of:

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

Try to use:

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


来源:https://stackoverflow.com/questions/5472254/reloading-navigation-properties-after-detaching-a-new-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!