SQL to Linq conversion with cross join

廉价感情. 提交于 2019-12-12 06:16:41

问题


Can someone please help in converting the following sql to linq in c#?

select s.SYSTEM_NAME,
       r.RESET_CODE,
       COUNT(v.reset_code) 
  from (select distinct system_name 
          from tbl) s 
cross join (select distinct reset_code 
              from tbl) r 
left join tbl v on v.SYSTEM_NAME = s.SYSTEM_NAME 
               and v.RESET_CODE=r.RESET_CODE 
 group by s.SYSTEM_NAME,r.RESET_CODE 

回答1:


Cross joins are generally represented as multiple from clauses in a query expression, or a call to SelectMany in extension method syntax.

So the first part of your query might be:

var query = from systemName in db.Table.Select(x => x.SystemName).Distinct()
            from resetCode in db.Table.Select(x => x.ResetCode).Distinct()
            ...

Left outer joins are usually represented with a "join ... into ..." query, possibly like this:

var query = from systemName in db.Table.Select(x => x.SystemName).Distinct()
            from resetCode in db.Table.Select(x => x.ResetCode).Distinct()
            join tmp in db.Table on 
                new { ResetCode = resetCode, SystemName = systemName } 
                equals new { tmp.ResetCode, tmp.SystemName }
                into tmpGroup
            select new { ResetCode = resetCode,
                         SystemName = systemName,
                         Count = tmpGroup.Count() };

I'm not sure about the Count part, to be honest... I'm not 100% sure what the COUNT(v.ResetCode) does in your original SQL.



来源:https://stackoverflow.com/questions/4715744/sql-to-linq-conversion-with-cross-join

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!