zoukankan      html  css  js  c++  java
  • Expression<Func<TObject, bool>>与Func<TObject, bool>的区别

    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<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>>。

    //正确的代码
    
    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);
    
  • 相关阅读:
    SQL Server -使用表触发器记录表插入,更新,删除行数
    利用DataSet部分功能实现网站登录
    SQL Server排序的时候使null值排在最后
    大数据操作:删除和去重
    C#匿名类型序列化、反序列化
    Js调用asp.net后台代码
    C# Excel
    ajax的介绍
    MySQL数据库的知识总结
    ASP.NET MVC 入门系列教程
  • 原文地址:https://www.cnblogs.com/wangbaohui/p/6900356.html
Copyright © 2011-2022 走看看