Entity framework .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()
,您就会从数据库中检索 所有 记录,而不仅仅是 "important" 记录。当您稍后执行 Where
子句时,为时已晚。
创建另一个方法,在调用 ToList()
之前使用 Where
进行过滤。
public List<Employee> GetImportantEmployees()
{
var employee = new ApplicationDBContext().Employee;
return employee.Where(e => e.IsImportant).ToList();
}
除此之外,我不确定您还可以做些什么来使您的 C# 代码更快。如果您只需要 "important" 名员工的子集(也在致电 ToList()
之前),请应用更多过滤器。
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()
,您就会从数据库中检索 所有 记录,而不仅仅是 "important" 记录。当您稍后执行 Where
子句时,为时已晚。
创建另一个方法,在调用 ToList()
之前使用 Where
进行过滤。
public List<Employee> GetImportantEmployees()
{
var employee = new ApplicationDBContext().Employee;
return employee.Where(e => e.IsImportant).ToList();
}
除此之外,我不确定您还可以做些什么来使您的 C# 代码更快。如果您只需要 "important" 名员工的子集(也在致电 ToList()
之前),请应用更多过滤器。