繁体   English   中英

使用交叉连接将SQL查询转换为linq到实体

[英]Translate a SQL query to linq to entity with a cross join

我必须将此SQL查询转换为linq到C#中的实体表达式。 通常,我使用Linqer来帮助我进行复杂查询,但是由于交叉联接,它无法正常工作。 我读到我需要SelectMany进行交叉连接,但我自己做不到。

这里的表达式:

select allds.DiscountId, allds.SKUId, max(case when ds.DiscountId is not null then 1 else 0 end) as HasPair
from (select distinct discount.Id as DiscountId, sku.Id as SKUId
      from Discounts discount cross join
           SKUs sku
     ) as allds left outer join
     DiscountSKUs ds
     on allds.DiscountId = ds.DiscountId and allds.SKUId = ds.SKUId
group by allds.DiscountId, allds.SKUId

查询将返回如下矩阵:

            10% discount | 15% discount | 25% discount
   SKU #1     Checked         NULL            NULL
   SKU #2     NULL            Checked         NULL
   SKU #3     Checked         NULL            Checked

谢谢您的帮助!!

LINQ中没有特殊的“交叉连接”运算符,这种构造很简单,无需连接

from a in tableA
from b in tableB
...

您的SQL查询应翻译成这样的形式(未经测试)

var query =
from allds in (from discount in db.Discounts
               from sku in db.SKUs
               select new { DiscountId = discount.Id, SKUId = sku.Id }
              ).Distinct()
join ds in db.DiscountSKUs
on new { allds.DiscountId, allds.SKUId } equals new { ds.DiscountId, ds.SKUId }
into discountSKUs
from ds in discountSKUs.DefaultIfEmpty()
group new { allds, ds } by new { allds.DiscountId, allds.SKUId } into g
select new
{ 
    g.Key.DiscountId,
    g.Key.SKUId,
    HasPair = g.Any(e => e.ds != null)
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM