【问题标题】:Subquery in Where Clause of LINQ statementLINQ 语句 Where 子句中的子查询
【发布时间】:2013-04-25 07:49:57
【问题描述】:

所以我尝试按照this 示例在此 LINQ 查询的 where 子句中添加子查询。

var innerquery =
    from app in context.applications
    select new { app.app_id };

IEnumerable<postDatedCheque> _entityList = context.postDatedCheques
    .Where(e => innerquery.Contains(e.appSancAdvice.application.app_id));

目标是从 postDatedCheques 中选择那些在 applications 表中具有 app_id 的记录。

但我在 where 子句中遇到以下错误:

  1. 委托“System.Func”不 取 1 个参数
  2. 无法将 lambda 表达式转换为“字符串”类型,因为它不是 委托类型
  3. “System.Linq.IQueryable”不包含 “包含”的定义和最佳扩展方法重载 'System.Linq.ParallelEnumerable.Contains(System.Linq.ParallelQuery, TSource)' 有一些无效参数
  4. 实例参数:无法从 'System.Linq.IQueryable' 到 'System.Linq.ParallelQuery'

我写错了什么?

【问题讨论】:

    标签: c# asp.net linq entity-framework linq-to-entities


    【解决方案1】:

    我认为一个简单的连接就可以完成这项工作。它将过滤掉没有相对“应用程序”的“支票”:

      var _entitylist = 
        from cheque in context.postDatedCheques
        join app in context.applications on cheque.appSancAdvice.application equals app
        select cheque;
    

    编辑:

    使用 .Contains(...) 的解决方案将被转换为 SQL IN 语句。这将是非常低效的。 Linq join 被翻译成 SQL INNER JOIN 如果你的 DB 模式被很好地修剪(FKs,索引),这非常有效

    【讨论】:

    • 这是一个更好的主意。谢谢。
    【解决方案2】:

    怎么样?

    IEnumerable<postDatedCheque> _entityList = context.postDatedCheques.Where(
         e => context.applications.Any(
              x => e.appSancAdvice.application.app_id == x.app_id));
    

    如果要使用两个语句,请将第一个设置为表达式函数。

    Expression<Func<string, bool>> innerQuery = 
              x => context.applications.Any(y => y.app_id == x);
    
    IEnumerable<postDatedCheque _entityList = 
      context.postDatedCheques.Where(
        x => innerQuery(x.appSancAdvice.application.app_id));
    

    【讨论】:

      【解决方案3】:

      innerquery 是一个匿名类型的 IQueryable,它包含一个 app_id
      Contains(e.appSancAdvice.application.app_id) 行没有意义,因为 e.appSancAdvice.application.app_id 和匿名类型不是同一类型。

      简单地做:

      var _entityList = context.postDatedCheques
                               .Where(e => 
                                  context.applications
                                         .Select(a => a.app_id)
                                         .Contains(e.appSancAdvice.application.app_id));
      

      【讨论】:

        【解决方案4】:

        试试这个:

        var innerquery =
            from app in context.applications
            select new { app.app_id };
        
        IEnumerable<postDatedCheque> _entityList = context.postDatedCheques
            .Where(e => innerquery.Any(a => a.app_id == e.appSansAdvice.application.app_id));
        

        【讨论】:

        • 应该是:[..] e =&gt; innerquery.Any(a =&gt; a.app_id == a.appSansAdvice.application.app_id) [..]
        • @Askolein,谢谢!
        猜你喜欢
        • 2020-12-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-05
        • 2016-10-06
        • 1970-01-01
        相关资源
        最近更新 更多