IQueryable 和 IEnumerable的扩展方法 一 我们从ef的DbSetT看起来,我们看到他继承了IQueryableT和 IEnumerableT 二 写了个例子,分别传入ExpressionFuncT,bool和FuncT,bool static void Main( string [] args) { Test U
IQueryable 和 IEnumerable的扩展方法
一
我们从ef的DbSet<T>看起来,我们看到他继承了IQueryable<T> 和 IEnumerable<T>
二
写了个例子,分别传入Expression<Func<T,bool>>和Func<T,bool>
static void Main(string[] args) { Test<Users> ut = new Test<Users>(); var q = ut.Find1(x => x.id == 1); var v = ut.Find2(x => x.id == 1); Console.ReadKey(); } public class Test<T> where T:class { // EF Entities dbEF = new Entities(); public virtual T Find1(Expression<Func<T, bool>> where1) { T _entity = dbEF.Set<T>().FirstOrDefault<T>(where1); return _entity; } public virtual T Find2(Func<T, bool> where2) { T _entity = dbEF.Set<T>().FirstOrDefault<T>(where2); return _entity; } }
查看运行结果:结果是一致的
我们看看他们的扩展实现:
Queryable
我们看到,其实通过Queryable扩展,我们传入了Expression<Func<T,bool>>
看一下sqlprofile
结果:查询时,通过Expression,我们直接组装成了带条件的sql语句进行查询。
Enumerable
我们看到,其实通过Enumerable扩展,我们传入了Func<T,bool>
看一下sqlprofile
结果:查询时,通过Func,我们直接查询了全表。
然后在全部结果加载到缓存后,我们才进行了id==1的筛选
所以结果很明显:
IQueryable 通过Expression拼接表达式树,然后组装sql语句进行滤查查询
IEnumerable 直接查询后,通过传入的Func方法,在缓存里进行过滤查询