简体   繁体   English

实体框架.ToList()慢吗? (全部查询)

[英]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. 一旦GetEmployees()执行ToList() ,您就会从数据库中检索所有记录,而不仅仅是“重要”记录。 By the time you execute the Where clause later on, it's too late. 等到稍后执行Where子句时,为时已晚。

Create another method, where you filter with Where before calling ToList() . 创建另一个方法,在调用ToList()之前使用Where进行过滤。

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. 除此之外,我不确定您还可以采取什么措施来提高C#代码的速度。 Apply more filters if you only need a subset of the "important" employees (also before calling ToList() ). 如果只需要一部分“重要”雇员(在调用ToList()之前ToList()应用更多过滤器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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