2013-04-25 102 views
0

所以我试着按照this的例子在这个LINQ查询的where子句中有一个子查询。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应用表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'

我是什么编码不正确的?

回答

4

我认为一个简单的加入会做这项工作。它会过滤掉了“检查”有没有相对“应用”:

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这是非常有效的,如果您的数据库架构修剪得很好(FKs,索引)

+0

这是一个更好的主意。谢谢。 – 2013-04-25 13:10:21

1

试试这个:

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)); 
+0

这项工作,不需要任何功能? – 2013-04-25 08:09:27

+2

应该是:[[..] e => innerquery.Any(a => a.app_id == a.appSansAdvice.application.app_id)[..]' – Askolein 2013-04-25 08:17:12

+0

@Askolein,谢谢! – lexeRoy 2013-04-25 08:20:21

1

innerquery是包含app_id匿名类型的IQueryable的。
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

那么呢?

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));