2011-05-31 111 views
1

很多搜​​索后,我无法找到一个简单的答案,这下面的SQL语句:转换普通SQL到LINQ到实体

SELECT t1.LoginName, t0.BNAME 
FROM USR02 AS t0 
LEFT OUTER JOIN LoginData AS t1 
    INNER JOIN Mandants AS t2 ON t1.Id_Mandants = t2.Id_Mandants 
ON t0.BNAME = t1.LoginName AND t0.MANDT = t2.CodeMandant 

由于双ON语句,我不知道怎么写的在LINQ中。

我试图简化它,但多个主键使工作很难。

+1

什么是你的方法这么远? – 2011-05-31 14:51:52

+0

注意事项:您的'LEFT JOIN'确实表现为'INNER JOIN' – a1ex07 2011-05-31 15:03:18

+0

嗨,Daniel,谢谢你的帮助。 Inner连接是绑定T2表和t1,结果用于使用T0创建左外连接来查找所有无法用T0映射的LoginData行。但是我需要T0中的所有行。 – Markus 2011-05-31 15:24:22

回答

0

您需要将您的查询转换为定期,1级加盟:

select t1.LoginName, t0.BNAME 
from USR02 as t0 
left outer join LoginData as t1 on t0.BNAME = t1.LoginName 
inner join Mandants as t2 on t0.MANDT = t2.CodeMandant and t1.Id_Mandants = t2.Id_Mandants 

那么这将是更容易把它改写了LINQ to实体:

from t0 in db.t0 
join t1 in db.t1 on t0.BNAME equals t1.LoginName 
join t2 in db.t2 on new { t0.MANDT, t1.Id_Mandants} equals new { t2.CodeMandant , t2.Id_Mandants } 
select new { t1.LoginName, t0.BNAME }; 
+0

嗨abatishchev,谢谢你的回答,重要的一点是我想要从USR02表中找到所有行,并找到所有的LoginData行为null。 – Markus 2011-05-31 15:11:51

2

开始通过翻译SQL查询更自然。就像这样:

SELECT t1.LoginName, t0.BNAME 
FROM USR02 AS t0 
     LEFT OUTER JOIN LoginData AS t1 
      ON t0.BNAME = t1.LoginName 
     INNER JOIN Mandants AS t2 
      ON t1.Id_Mandants = t2.Id_Mandants 
WHERE t0.MANDT = t2.CodeMandant 

现在,应该是很容易这个转换为LINQ。如果您已经正确设置了实体模型中的关系,则可以编写以下LINQ查询:

from data in db.LoginData 
where data.User.MANDT == data.Mandant.CodeMandant 
select new { data.LoginName, data.User.BNAME }; 

btw。为什么你输出LoginData.LoginName作为USR02.BNAME,因为它们总是相等的?

+0

嗨史蒂文,谢谢你的回答。我认为引起我的麻烦的是“ON t0.BNAME = t1.LoginName AND t0.MANDT = t2.CodeMandant”这一行很重要。 – Markus 2011-05-31 15:19:46

0

我喜欢写作加入这样

from t0 in db.t0 
from t1 in db.t1.Where(x => t0.BNAME == x.LoginName).DefaultIfEmpty() 
from t2 in db.t2.Where(x => t0.MANDT == x.CodeMandant) 
       .Where(x => t1.Id_Mandants == x.Mandants) 
select new { t1.LoginName, t0.BNAME };