views:

23

answers:

1

Hi,

I am creating a webapp using entity framework 4. As far as I can tell from extensive googling, it is best practice to create and kill the objectcontext when it is being used, and not let it live too long. So in my datalayer, I am doing something like:

using (var context = new MyDAO()) { MY CODE } creating and killing the context right away.

One of the things I like about entity framework is the ability to work with related objects directly in your code (eg. Account.Employees). The problem is, that when I try to do this in my presentationlayer, it throws an exception since the context is no longer available, so it cannot fetch the employees for the account. I have tried enabling lazyloading on the context in my datalayer, but it doesn't seem to work.

So my questions is, how do I get the relationships (lazy)loaded across different tiers?

Thanks Thomas

A: 

You have to load everything you need before closing the context.

This is a design decision in EF. That any loading of objects should be controlled rather than happening indirectly. This generally gives a more scalable solution.

edit

Thanks for the comment.

These settings are on the context. So you still need to have the context open. One way to do this would be to open the context at the top layer and send it down as a parameter.

Shiraz Bhaiji
Thanks. I thought this had changed in EF4 with self-tracking entities and the LazyLoadingEnabled-setting (http://msdn.microsoft.com/en-us/library/dd456846.aspx)?
Thomas
How would that best be handled throughout the app? Eg. would it mean that the context should live for the user's entire session, per page or something else and if so, how would that affect performance? Thanks
Thomas