Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lazy loading properties after an insert

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.

like image 946
user472292 Avatar asked Dec 28 '22 19:12

user472292


1 Answers

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.

like image 50
Slauma Avatar answered Jan 17 '23 22:01

Slauma