Basically I have a Repository that controls access to my EF model. It creates the reference and then depending on the Repository being accessed, returns the Entity that was requested. Right now I am exposing an IQueryable Get method that will return the Entity directly off the live ObjectContext. Good practice tells me that I should wrap any ObjectContext use inside using statement to make sure it is properly disposed, but when I do this from the Repository I get an error that the ObjectContext has already been disposed by the time the controller loads it. I've removed the using and then it works just fine, but I'd like to know how one should normally approach this. I would like to maintain an IQueryable return as I may need to perform various commands on it. Any suggestions? Does EF help protect me from hitting open connections if multiple HTTP requests start coming in?
Errors out:
public IQueryable<IUser> Get
{
get
{
using (var context = new DrinkersPassportEntities(_connString))
{
return context.Users.AsQueryable();
}
}
}
Works but doesn't help me sleep at night:
public IQueryable<IUser> Get
{
get
{
var context = new DrinkersPassportEntities(_connString);
return context.Users.AsQueryable();
}
}
All my controller is doing at the moment is this:
public ViewResult Index( )
{
return View(userRepo.Get);
}
Some people will tell you your repository shouldn't return Queryables....but I don't buy that.
You do indeed want to make sure you dispose of the ObjectContext or you can end up with a memory leak (especially since it holds on to all of the materialized entities).
A common solution is to use a per-request ObjectContext lifetime. That is, store the ObjectContext in the Request object of ASP .NET and handle the HttpApplication.EndRequest event, at which time you dispose the ObjectContext.