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?
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. :)
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With