开发者

Attaching an object to another context in EF 4

开发者 https://www.devze.com 2023-02-08 02:07 出处:网络
I have a baseclass in my website with a property: CurrentUser. The get method of this property will create a new context and get a User object from the database based on auth cookie information. So fa

I have a baseclass in my website with a property: CurrentUser. The get method of this property will create a new context and get a User object from the database based on auth cookie information. So far so good.

But since the context is closed, all I can do outside this, is to call properties directly under User, for example FirstName.

But as soon as I try to get a relation for example, like CurrentUser.UserOffices this won't work since I didn't include UserOffices in the query.

Is there a way to create a new context outside the baseclass which I can attach the CurrentUser object to? I have tried ctx.Attach(CurrentUser) with no luck.

You may wonder why I don'开发者_开发技巧t include UserOffices. This is simply because there are very many relations to different tables and I don't want to include them all since it differs between my web pages what relations are needed.

Any ideas?


You can try to Attach your entity and then explicitly load property:

ctx.Attach(CurrentUser);
ctx.LoadProperty(CurrentUser, u => u.UserOffices);

I'm not sure if this works with POCOs.

You can also query for object again with Includes specifing navigation properties you need.

The other choice is simply load UserOffices with Linq-to-entities query restricting where condition to current user.

0

精彩评论

暂无评论...
验证码 换一张
取 消