Func<TObject, bool>是委托(delegate)
Expression<Func<TObject, bool>>是表达式
Expression编译后就会变成delegate,才能运行。比如
Expression<Func<int, bool>> ex = x=>x < 100;
Func<int, bool> func = ex.Compile();
然后你就可以调用func:
func(5) //-返回 true
func(200) //- 返回 false
而表达式是不能直接调用的。
案例:不正确的查询代码造成的数据库全表查询。
错误代码如下:
将 Func 类型的变量作为参数传给Count 方法吗,EF 会将整个表的所有数据查询出来,从内存里面做筛选。生成的 sql 语句如下:
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (8ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT [c].[id], [c].[client_type], [c].[status], [c].[tenant]
FROM [table] AS [c] 正确的代码如下:
正确的写法会从数据库中加 where 条件,然后,直接返回 count 的值。生成的 sql 语句如下:
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (4ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT COUNT(*)
FROM [table] AS [c]
WHERE [c].[client_type] = 1
使用 Func 委托调用的是 System.Linq.Enumerable 下面的 Count
使用 Expression<Func<T, bool>> 表达式调用的是 System.Linq.Queryable 下面的 Count
(完)
|