当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - EF doesn't update related entities on SaveChanges

问题描述:

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

网友答案:

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: