【问题标题】:how to access table from embedded where LINQ c#如何从嵌入式 LINQ c# 访问表
【发布时间】:2016-07-21 07:43:33
【问题描述】:

请注意,下面的内容完全是虚构的,例如清酒。我有一个基于 sql 代码的类似查询,但无法将其转换为 LINQ 以获得正确的值。

sql基本上是这样的:

select * from customers c
join proucts p on c.id = p.customerid
join credit r on r.customerid=c.id and ISNULL(r.trandate, c.registeredDate) >= c.registeredDate

我还尝试调整上面的 sql 并将条件放在 where 中,它还返回我在下面的 #2 LINQ 中得到的相同值(这是不正确的)。

如何在 .Where of credit 中使用 c(客户)?看代码

1.

from c in customers
join p in products on c.id = p.customerid
join cr in credit.Where(r=> r.tranDate => c.registeredDate!=null?c.registeredDate : r.purchaseDate)   on c.id=cr.customerid
...

2.

我知道你会建议为什么不把它放在下面的地方,但我得到的值不正确。

from c in customers
join p in products on c.id = p.customerid
join cr in credit on c.id=cr.customerid
where r.tranDate => c.registeredDate!=null?c.registeredDate : r.purchaseDate

有解决方法吗?我已经尝试了很多其他方法,但都找不到正确的方法。

【问题讨论】:

    标签: c# linq where


    【解决方案1】:

    LINQ 仅支持等值连接。任何其他标准都应转到where 子句。是的,其他范围变量无法从join 内部序列中访问,因此过滤应该发生在join 之前或之后。

    所以这个 SQL 查询:

    select * from customers c
    join products p on c.id = p.customerid
    join credit r on r.customerid = c.id
        and ISNULL(r.trandate, c.registeredDate) >= c.registeredDate
    

    直接翻译成这个 LINQ 查询:

    from c in customers
    join p in products on c.id equals p.customerid
    join cr in credit on c.id equals cr.customerid
    where (cr.tranDate ?? c.registeredDate) >= c.registeredDate
    select new { c, p, cr };
    

    可选条件

    (cr.tranDate ?? c.registeredDate) >= c.registeredDate
    

    可以替换为

    (cr.tranDate == null || cr.tranDate >= c.registeredDate)
    

    【讨论】:

      猜你喜欢
      • 2013-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-08
      • 2015-10-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多