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

时间:2015-12-11 20:15:38

标签: c# sql entity-framework linq

我必须将此SQL查询转换为C#中的linq to entity表达式。通常我使用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

感谢您的帮助!!

1 个答案:

答案 0 :(得分:1)

没有特殊的"交叉连接" 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)
};