Reloading navigation properties after detaching a

2019-08-15 17:23发布

问题:

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";