Reputation: 1737
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?
Upvotes: 6
Views: 1813
Reputation: 5081
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.
Upvotes: 1
Reputation: 39916
Let's consider typical usage pattern of user, you will never just open one item and go away, in fact we move back and forth between items, search and review items again, modify and save them.
If you keep your ObjectContext alive for entire session, you will use little more memory per user, but you will reduce your application to database transfers, and you will be able to accumulate changes. And save changes at once. Since EF implements Identity Pattern, you will not be loading multiple copies of same object.
Otherwise if you dispose ObjectContext, will reduce memory but will increase overhead of loading objects again and again. You might be loading multiple copies of same object again and again over views and increasing query load on database server.
Upvotes: 0
Reputation: 156524
I assume you're talking about disposing the Entity Framework "Contexts," since the objects themselves aren't disposable.
We've found it best to leave the entities themselves in our data layer and map them to POCOs/DTOs that contain all the information we need for a given view. That way we're not trying to lazy-load data while we render our view. We wrap the data-access code in a using(var context = contextFactory.Get())
, so that the context will automatically be disposed before the method ends, but after we have loaded all the data we're retrieving into an in-memory collection.
Upvotes: 0