Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC and Entity Framework when to Dispose Entity objects

When do you dispose an Entities object context objects in entity framework and MVC?

For example if I have a persons table and I select a record in a controller method, dispose it and pass it back to my view, then the record won't be usable in the view.

Should I be disposing it somehow after my view is processed? or not disposing it at all?

like image 608
Tija Avatar asked May 18 '11 17:05

Tija


1 Answers

One option is to create it in Global.asax's begin request event, and dispose of it in Global.asax's end request event. Every page simply uses that one (stored and obtained in HttpContext.Current.Items or in thread local storage) without disposing it. That lets it be available to your view to do lazy loading but still disposes of it after the request is completed.

The other option is to make sure everything you need is already loaded before calling your view (via .First(), .ToList(), and .Include(property) to include navigation property data) and dispose of it immediately. Both methods work.

like image 196
Tridus Avatar answered Oct 03 '22 02:10

Tridus