如何将leftouterjoin查询转换为LINQ

时间:2012-05-10 06:40:43

标签: c# sql linq

我有一个sql查询,它有innerjoin和leftouter join,这对于转换为LINQ非常棘手。

SELECT project.ID, project.No, project.Name,  
       APPLN.Id,APPLN.Name,SAR.Name  
FROM Phasefact phase WITH (NOLOCK)  
INNER JOIN AProject project WITH (NOLOCK) on phase.Id = project.ID
INNER JOIN Application APPLN WITH (NOLOCK) ON project.AppId = APPLN.Id
LEFT OUTER JOIN Master master WITH (NOLOCK) ON phase.amId = master.Id
INNER JOIN Ref SAR WITH (NOLOCK) ON SAR.ID = master.Ref_Id
WHERE phase.ID = 123    

它有点令人困惑,因为它包含“左外连接”。有人请帮忙。

2 个答案:

答案 0 :(得分:2)

也许是这样的:

var result=(
        from phase in db.Phasefact
        join project in db.AProject
            on phase.Id equals project.ID
        join APPLN in db.Application 
            on project.AppId equals APPLN.Id
        //Left join
        from master in db.Master
            .Where(a=>a.Id==phase.amId).DefaultIfEmpty()
        join SAR in db.Ref
            on SAR.ID equals master.Ref_Id
        where phase.ID == 123 
        select new
        {
            project.ID,
            project.No,
            project.Name,  
            APPLN.Id,
            APPLN.Name,
            SAR.Name
        }
    );

修改

但我没有得到left join。你为什么使用left join?对我而言,您似乎首先使用left join

LEFT OUTER JOIN Master master WITH (NOLOCK) ON phase.amId = master.Id

之后你有一个限制结果的联接:

INNER JOIN Ref SAR WITH (NOLOCK) ON SAR.ID = master.Ref_Id

这与执行此操作相同:

INNER JOIN Master master WITH (NOLOCK) ON phase.amId = master.Id
INNER JOIN Ref SAR WITH (NOLOCK) ON SAR.ID = master.Ref_Id

答案 1 :(得分:0)

我给你一个关于LINQ中左外连接的基本概念

  

var lines =来自db.Phasefact中的p   在m.Id等于db.Master中加入m   p.amId into p_m   其中p.ID == 123   来自m in p_m.DefaultIfEmpty()   选择新的{p.ID};

现在你可以根据你的逻辑更新这个......或者查询.......