LINQ错误:从范围''引用的'y'类型的变量'x',但未定义

时间:2011-02-24 18:09:03

标签: c# linq join reference subquery

我遇到了这个错误...

变量'paymentLine'类型'Xrm.sb_directdebitpaymentline'从范围''引用,但未定义

...当我尝试在以下代码后执行'paymentLines.ToList()'时:

var payments = from payment in Crm.sb_directdebitpayments
               where payment.statuscode == 1
                     && Crm.sb_directdebitmandates.Any(mandate =>
                                                       mandate.sb_directdebitmandateid ==
                                                       payment.sb_directdebitmandateid &&
                                                       mandate.statuscode == 1)
               select payment;

var paymentLines = from paymentLine in Crm.sb_directdebitpaymentlines
                   where paymentLine.sb_paymentsent == isSent
                         && paymentLine.statuscode == status
                         && payments.Any(payment =>
                                         payment.sb_directdebitpaymentid ==
                                         paymentLine.sb_directdebitpaymentid &&
                                         payment.statuscode == 1)
                   select paymentLine;

如果有人对如何解决这个问题有任何想法,我将非常感激!

3 个答案:

答案 0 :(得分:2)

这是查询语法和扩展方法(Any)的奇妙组合。

它看起来像捕获循环var 问题的变体。 paymentLines的执行被推迟,因此在执行paymentLine时捕获的payments.Any( )行有什么价值?

尝试将其重写为Join。

答案 1 :(得分:1)

我曾尝试将此作为一个联接写入,但失败了。但是我今天重新审视并弄清楚我做错了什么;它与where子句的顺序有关(事实上我需要一段时间才能解决,我甚至需要多个where子句!)。谢谢你的所有答案。解决方案是:

var paymentLines = from paymentLine in Crm.sb_directdebitpaymentlines
                   join payment in Crm.sb_directdebitpayments on paymentLine.sb_directdebitpaymentid equals payment.sb_directdebitpaymentid
                   join mandate in Crm.sb_directdebitmandates on payment.sb_directdebitmandateid equals mandate.sb_directdebitmandateid
                   where mandate.statuscode == 1
                   where payment.statuscode == 1
                   where paymentLine.sb_paymentsent == isSent && paymentLine.statuscode == status
                   select paymentLine;

答案 2 :(得分:-1)

我认为您无法在Any()之前致电Select,因为Any()会返回boolean值。我会将Any()中的所有代码放在Where中,然后在Any()子句之前检查foreach

if (paymentLines.Any())
  {
foreach (var n in paymentLines)
         {
           //Do work
         }
  }