I have created a simple repository class that is returning a list of Projects:
public class ProjectRepository : IProjectRepository
{
public IQueryable<Project> GetProjects()
{
DbEntities db = new DbEntities();
return db.Projects;
}
}
I have some code later down the line that is working off this IQueryable to do some sorting/paging:
public ActionResult Index()
{
var projectList = (from p in projectRepository.GetProjects()
orderby p.Name
select p).Take(20);
return View(projectList.ToList());
}
I originally wrapped my GetProjects() call in a using statement out of habit – since it’s usually a good idea to dispose your objects as soon as possible. This caused problems understandably because I was doing some further database work in my controller action.
Is it okay to just let the object be disposed when it is garbage collector? Is there a better way to do this instead? Should I be creating more targeted repository methods like:
public IQueryable<Project> GetProjects(int takeThisMany)
{
return (from p in db.Projects
orderby p.Name
select p).Take(takeThisMany);
}
Is it a good or bad practice to return IQueryable objects that will be executed at a later time in a controller action without disposing the original context or not?
It’s fine to return
IQueryable<T>, but wrong to either not dispose anObjectContext(you should always dispose anyIDisposable) or to dispose it before the request is complete.Use constructor injection to pass the context to the repository and dispose it at the end of the request.