繁体   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);

在性能方面,这种方法可行吗? 有什么解决方案可以使其快速运行吗? 谢谢!

一旦GetEmployees()执行ToList() ,您就会从数据库中检索所有记录,而不仅仅是“重要”记录。 等到稍后执行Where子句时,为时已晚。

创建另一个方法,在调用ToList()之前使用Where进行过滤。

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

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

除此之外,我不确定您还可以采取什么措施来提高C#代码的速度。 如果只需要一部分“重要”雇员(在调用ToList()之前ToList()应用更多过滤器。

暂无
暂无

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

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