I have a parent and child object. 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 doing this? If I get a new context (after saving), I can see Parent just fine.
I guess you are working with lazy loading enabled. If you want that the navigation property gets populated after adding the object with the foreign key property to the context you must use the Create
method of DbSet
(instead of instantiating the object with new
):
Child c = context.Child.Create();
With active lazy loading this will create a proxy object which ensures that the navigation property gets loaded.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With