views:

1700

answers:

2

I'm thinking it would be smart to setup the Entity object context in Application_BeginRequest, store it in Request.items, use it throughout the request and dispose it in Application_EndRequest. That way the context is always available and I can navigate the Entity Framework object graph in my views, lazy loading what I haven't already eager fetched.

I think this would make it like developing on Ruby on Rails.

It might be I should be shot for speaking such heresy, but it's so crazy it just might work :)

I can't get Application_BeginRequest and ..EndRequest to fire on ASP.NET MVC though. Aren't they fired? Any special trick I need to do?

+5  A: 

The object context in EF, like the data context in L2S, is designed as a "unit of work", They're not thread-safe, and they're not designed to be long lived.

In MVC, the best strategy is to create one in the controller's constructor (implicitly or explicitly, doesn't matter) and then dispose it in the Dispose method. Of course, EF doesn't do lazy loading, so you'll have to find your own way to be lazy. :)

Brad Wilson
No, this a bad approach. It makes the Controller hard to test and also means the unit of work is not available outside of the Controller. The Session-per-request pattern mentioned below is better. EF v1 does support lazy loading - it just has to be explicit.
Andrew Peters
I think you misunderstand what "lazy loading" means. EF allows you to automatically eagerly load relationships, but not lazy load.As for testability, I agree that directly consuming an object context hurts testability, but that has nothing to do with ctor/dispose usage.
Brad Wilson
LOL dude. It just has to be "explicit" http://blogs.msdn.com/jkowalski/archive/2008/05/12/transparent-lazy-loading-for-entity-framework-part-1.aspx
Andrew Peters
+5  A: 

The 1.0 build of ASP.NET MVC let me hook up event handlers on both beginrequest and endrequest, newing up a SessionScope and storing it in HttpContext.Items in beginrequest (I switched to Castle ActiveRecord) and in endrequest I pick the sessionscope out from HttpContext.Items and dispose it. This enables lazy loading throughout the request lifecycle. (can even navigate object graph in views.)

AndreasKnudsen