Reputation: 3397
I have a class that contains several common methods customized for use in my MVC app, that I use in several places. Here is an example of some:
private MyEntities db = new MyEntities();
public List<SelectListItem> GetLocationList()
{
var query =
db.v_LocationsAlphabetical.OrderByDescending(x => x.Category).ThenBy(x => x.LocationName).ToList()
.Select(x => new SelectListItem
{
Value = x.LocationID.ToString(),
Text = x.LocationName
});
return (query).ToList();
}
public IEnumerable<SelectListItem> GetStates()
{
var query = db.States.Select(x => new SelectListItem
{
Value = x.Abbr,
Text = x.Name
});
return(query);
}
public List<Person> GetPeople()
{
var query = db.Person.OrderBy(m => m.LastName).ThenBy(m => m.FirstName).ToList();
return (query);
}
Each one of these methods makes a call to the database to get data and I was wondering if I need to add a dispose to each method. If not, why? Thanks.
Upvotes: 3
Views: 2235
Reputation: 21477
No. DbContexts don't have to be manually disposed, unless you manually manage the connection yourself. Therefore, disposing them is usually optional.
Upvotes: 0
Reputation: 13600
There are multiple ways of handling db connection in .NET
One of my favorites is the one called one dbcontext per request
, which basically means you initialize your dbcontext when needed, do the work without thinking about instantiating or disposing, and dispose automatically when the request is done. (kinda UnitOfWork-ish)
I've already shown this approach here. It's not only applicable to EF, but to Linq2SQL, ADO.NET, etc. as well.
Upvotes: 0
Reputation: 86084
You shouldn't call dispose in each method, because the lifetime of db
is the same as that of the enclosing class since it's not a local variable in a method.
The typical way to handle this is to make the current class IDisposable
and call db.Dispose()
in the Dispose()
method.
Upvotes: 6