jmvtrinidad
jmvtrinidad

Reputation: 3658

Entity framework .ToList() is slow? (Query all)

public List<Employee> GetEmployees(){
     var employee = new ApplicationDBContext().Employee;

     return employee.ToList();
}

//somewhere in other part of code.
//Use GetEmployees.
var employees = GetEmployees();
var importantEmployees = employees.Where(e => e.IsImportant == true);

In terms of performance, this method is feasible? Is there any solution to make it fast? Thanks!

Upvotes: 1

Views: 2044

Answers (1)

Grant Winney
Grant Winney

Reputation: 66439

As soon as GetEmployees() executes ToList(), you retrieve all the records from the database, not just the "important" ones. By the time you execute the Where clause later on, it's too late.

Create another method, where you filter with Where before calling ToList().

public List<Employee> GetImportantEmployees()
{
    var employee = new ApplicationDBContext().Employee;

    return employee.Where(e => e.IsImportant).ToList();
}

Other than that, I'm not sure what else you can do to make it faster from your C# code. Apply more filters if you only need a subset of the "important" employees (also before calling ToList()).

Upvotes: 7

Related Questions