Consider the following code snippets:
public interface IRepository<T> where T : class
{
IQueryable<T> GetAll();
...
}
public class EmployeeRepository<T> : IRepository<T> where T : class
{
private Employee db;
private DbSet<T> dbSet;
public EmployeeRepository()
{
db = new Employee();
dbSet = db.Set<T>();
}
public virtual IQueryable<T> GetAll()
{
return dbSet;
}
}
In the controller I implement it as:
private IRepository<Employee> employeeRepo = null;
public HomeController()
{
employeeRepo = new EmployeeRepository<Employee>();
}
Using the above code if I call the employeeRepo.GetAll()
method in my MVC controller action I get the result instantly in the view No more than 2 seconds to return the records of around 500 rows. If I change the same code to
public virtual IEnumerable<T> GetAll()
{
return dbSet.ToList();
}
then it takes about 30 seconds to return the same amount of rows from the exact same table.
So my question is why does IEnumerable<T>
take so much longer than IQueryable<T>
.
Most of the example I've seen online for repository-pattern use IEnumerable<T>
so I'm not sure if I'm going down the correct route by using IQueryable<T>
Update:
public ActionResult Index()
{
var allEmployees = employeeRepo.GetAll();
return View(allEmployees);
}
The SQL being executed is
SELECT EMPLOYEEID, EMPLOYEENAME, EMPLOYEEDOB, EMPLOYEETELEPHONE FROM [DBO].[EMPLOYEE]
The exact number of rows returned is 507. I use all of them because they will go into a dropdown list