简体   繁体   中英

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!

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() ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM