Question

I'm migrating my EF6 MVC project from ObjectContext to DbContext with lazy loading.

With ObjectContext, I could do the following:

// Create a new user:
 User u = new User();
 u.LineManagerID = 42;   // Set foreign key

 db.Users.Add(u);
 db.SaveChanges();

// get property of related entity as set above by foreign key 
 User lm = u.LineManager;

With DbContext, u.LineManager is null even the the new entity is saved correctly and I suspect if I did another call to the database it would be fine.

Lazy loading and dynamic proxies are both enabled.

Why doesn't the new entity refresh properly?

Please help! I can see this migration is going to be lot harder than I thought...!

EDIT - I should add that I am using db-first code generation

Was it helpful?

Solution

You have to make the LineManager property virtual to be overridable by the lazy loading proxy. (which it already is thanks to the code generation)

When you are creating the object directly with new you are unfortunately just creating a plain object - not the proxy one with all the lazy loading features. To get those, you need to use a factory method to create your object:

User u = db.Users.Create();

I did some experimenting with navigation properties and foreign keys that I documented in a blog post.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top