Lazy loading properties after an insert

那年仲夏 提交于 2020-01-10 03:07:46

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/6312981/lazy-loading-properties-after-an-insert

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