Lazy boot properties after insertion

I have a parent and a child. If I do the following

Child c = new Child(); c.ParentID = parentID; context.Child.Add(c); context.SaveChanges(); int i = c.Parent.ParentID; // throws an exception b/c Parent is null 

Why is this so? If I get a new context (after saving), I can see that the Parent is just fine.

+4
entity-framework
Jun 10 '11 at 23:20
source share
1 answer

I think you are working with lazy loading. If you want the navigation property to be filled after adding an object with a foreign key to the context, you should use the Create DbSet method (instead of creating an instance of the object using new ):

 Child c = context.Child.Create(); 

With active lazy loading, this will create a proxy object that guarantees loading of the navigation property.

+9
Jun 11 2018-11-11T00:
source share



All Articles