Expression<Func<T, bool>>与Func<T, bool>的区别

转自:http://www.cnblogs.com/wow-xc/articles/4952233.html



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

而表达式是不能直接调用的。

===========================

案例:不正确的查询代码造成的数据库全表查询。

1
2
3
4
5
6
7
8
9
10
11
12
//错误的代码
Func<QuestionFeed,  bool > predicate =  null ;
if  (type == 1)
{
     predicate = f => f.FeedID == id && f.IsActive ==  true ;
}
else
{
     predicate = f => f.FeedID == id;
}
//_questionFeedRepository.Entities的类型为IQueryable<QuestionFeed>
_questionFeedRepository.Entities.Where(predicate);

上面代码逻辑是根据条件动态生成LINQ查询条件,将Func类型的变量作为参数传给Where方法。

实际上Where要求的参数类型是:Expression<Func<TSource, bool>>。

解决方法:

不要用Func<TSource, bool>,用Expression<Func<TSource, bool>>。

1
2
3
4
5
6
7
8
9
10
11
//正确的代码
Expression<Func<QuestionFeed,  bool >> predicate= null ;
if  (type == 1)
{
     predicate = f => f.FeedID == id && f.IsActive ==  true ;
}
else
{
     predicate = f => f.FeedID == id;
}
_questionFeedRepository.Entities.Where(predicate);

  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值