jmv*_*dad 1 c# entity-framework dbcontext
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);
Run Code Online (Sandbox Code Playgroud)
在性能方面,这种方法是否可行?有没有解决方案让它快速?谢谢!
一旦GetEmployees()执行ToList(),您将从数据库中检索所有记录,而不仅仅是"重要"记录.当你Where稍后执行该条款时,为时已晚.
创建另一个方法,Where在调用之前过滤ToList().
public List<Employee> GetImportantEmployees()
{
var employee = new ApplicationDBContext().Employee;
return employee.Where(e => e.IsImportant).ToList();
}
Run Code Online (Sandbox Code Playgroud)
除此之外,我不知道你还能做些什么来使你的C#代码更快.如果您只需要"重要"员工的一部分(也在致电之前ToList()),请应用更多过滤器.