Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
566 views
in Technique[技术] by (71.8m points)

entity framework - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...