使用literal的连接将SQL结果转换为LINq

时间:2017-03-23 17:22:31

标签: sql linq join

全部,   这是我在这个论坛上的第一篇文章,我在整个网站上搜索了所有问题的答案,但看起来没有我需要做的例子。

下面是我需要适应LINQ语句的SQL查询:

select COUNT(pe2.*)
from SomeTable pe1 
inner join SomeTable pe2 on (pe2.Id=pe1.Id and pe2.TypeCode='X')
where pe1.TypeCode='Y'

我试图加入这个,如下图所示,但它不起作用:

var query = (from pe2 in SomeTable
         join pe1 in SomeTable
         on new { pe1.Id } equals new {pe2.Id }
         where pe2.TypeCode == "X" 
         && pe1.TypeCode == "Y"
         select pe2).Count();

1 个答案:

答案 0 :(得分:0)

由于TypeCode是HardCoded,您可以将其传递给where子句

select pe2.*
from SomeTable pe1 
inner join SomeTable pe2 on pe2.Id=pe1.Id
where pe1.TypeCode='Y'
and pe2.TypeCode='X'

这就是我在linq

中的表现
var l1 = new List<dynamic> { new { Id = 1, Code = "X" }, new { Id = 2, Code = "Y" } };
var l2 = new List<dynamic> { new { Id = 1, Code = "Y" }, new { Id = 2, Code = "X" } };

//lambda expression
l1.Join(l2, 
        x => x.Id, 
        y => y.Id, 
       (x, y) => new { Pe1 = x,  Pe2 = y })
  .Where(x => x.Pe1.Code == "Y" && x.Pe2.Code == "X")
  .Select(x => x.Pe2);

//query...
from x in l1
join y  in l2 on x.Id equals y.Id
where x.Code == "Y" 
&& y.Code == "X"
select y

from x in l1
from y in l2
where x.Id == y.Id
&& x.Code == "Y"
&& y.Code == "X"
select y