Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC with Entity Framework

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?

like image 507
AndreasKnudsen Avatar asked Nov 11 '08 07:11

AndreasKnudsen


2 Answers

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. :)

like image 65
Brad Wilson Avatar answered Nov 19 '22 14:11

Brad Wilson


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.)

like image 27
AndreasKnudsen Avatar answered Nov 19 '22 15:11

AndreasKnudsen