Waq*_*qar 7 c# linq entity-framework
什么是明智地编写查询性能的最佳方法.例如,我可以编写查询以获得具体姓氏的所有雇员,如下所示
ObjectQuery<Employee> queryEmp =
context.CreateQuery<Employee>(
"Select value e from Employees AS e Where e.LastName = @lastName",
new ObjectParameter("lastName", typeof(String)) { Value = "Farooqi" });
ObjectResult<Employee> results = query.Execute(MergeOption.AppendOnly);
Run Code Online (Sandbox Code Playgroud)
要么
var v = from e in context.Employees where e.LastName == "Farooqi" select e;
Run Code Online (Sandbox Code Playgroud)
要么
context.Employees.Where(e => e.LastName == "Farooqi");
Run Code Online (Sandbox Code Playgroud)
要么
context.Employees.Where("LastName = @lastName", new ObjectParameter("lastName", typeof(String)) { Value = "Farooqi" });
Run Code Online (Sandbox Code Playgroud)
我的问题是,哪种查询方法最好.我感到困惑的是,我认为(但不确定)使用除了第一个方法之外的最后三个方法将从数据库中获取员工的所有记录,然后通过枚举将被回收的所有记录来满足指定的where条件,所以我认为最后三种方式比第一种方式花费更多时间,所以我只使用第一种方式.但实际上最好的是什么我不知道.是否所有方法只获取记录表格数据库,该数据库满足条件或从db获取所有记录,然后在应用程序结束时枚举返回过滤后的记录?
差别不大; 第二个/第三个具有在编译时强制类型正确性的优点,因为表达式树如果LastName不存在则不会编译或者(例如)int- 避免拼写错误和"魔术字符串"的问题.
重新考虑把所有东西带回来; 没有.第二个/第三个编译到表达式树,可以解构并用于创建正确的SQL(在服务器上执行过滤器).非常聪明,但经常被误解.关键是这是Queryable.Where(拿a Expression<Func<T, bool>>),而不是Enumerable.Where(拿a Func<T, bool>).随意执行跟踪.
同样,第1个/第4个之间几乎没有差别 - 两者都将在服务器上进行过滤.
| 归档时间: |
|
| 查看次数: |
1406 次 |
| 最近记录: |