简体   繁体   中英

LINQ multiple joins with one left join

I am fairly new to LINQ and I am struggling to make a multiple JOIN. So, this is how my database structure looks like:

在此输入图像描述

Now, how should my query look like, if I have a particular Grade and I want to select {Student.IndexNo, GradeValue.Value}, but if there is no grade value for a particular grade and particular user, null should be returned (Left join)?

The trick to get a LEFT join is to use the DefaultIfEmpty() method:

var otherValue = 5;

var deps = from tbl1 in Table1
           join tbl2 in Table2
              on tbl1.Key equals tbl2.Key into joinGroup
           from j in joinGroup.DefaultIfEmpty()
           where 
               j.SomeProperty == "Some Value"
               && tbl1.OtherProperty == otherValue
           select j;

Deliberately posting this in 2015 for newbies looking for solution on google hits. I managed to hack and slash programming my way into solution.

var projDetails = from r in entities.ProjekRumah
join d in entities.StateDistricts on r.ProjekLocationID equals d.DistrictID
join j in entities.ProjekJenis on r.ProjekTypeID equals j.TypeID
join s in entities.ProjekStatus on r.ProjekStatusID equals s.StatusID
join approvalDetails in entities.ProjekApproval on r.ProjekID equals approvalDetails.ProjekID into approvalDetailsGroup
from a in approvalDetailsGroup.DefaultIfEmpty()
select new ProjectDetailsDTO()
       {
        ProjekID = r.ProjekID,
        ProjekName = r.ProjekName,
        ProjekDistrictName = d.DistrictName,
        ProjekTypeName = j.TypeName,
        ProjekStatusName = s.StatusName,
        IsApprovalAccepted = a.IsApprovalAccepted ? "Approved" : "Draft",
        ProjekApprovalRemarks = a.ApprovalRemarks
};

Produces following SQL code internally

{SELECT [Extent1].[ProjekID] AS [ProjekID]
    ,[Extent1].[ProjekName] AS [ProjekName]
    ,[Extent2].[DistrictName] AS [DistrictName]
    ,[Extent3].[TypeName] AS [TypeName]
    ,[Extent4].[StatusName] AS [StatusName]
    ,CASE 
        WHEN ([Extent5].[IsApprovalAccepted] = 1)
            THEN N'Approved'
        ELSE N'Draft'
        END AS [C1]
    ,[Extent5].[ApprovalRemarks] AS [ApprovalRemarks]
FROM [dbo].[ProjekRumah] AS [Extent1]
INNER JOIN [dbo].[StateDistricts] AS [Extent2] ON [Extent1].[ProjekLocationID] = [Extent2].[DistrictID]
INNER JOIN [dbo].[ProjekJenis] AS [Extent3] ON [Extent1].[ProjekTypeID] = [Extent3].[TypeID]
INNER JOIN [dbo].[ProjekStatus] AS [Extent4] ON [Extent1].[ProjekStatusID] = [Extent4].[StatusID]
LEFT JOIN [dbo].[ProjekApproval] AS [Extent5] ON [Extent1].[ProjekID] = [Extent5].[ProjekID] 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM