我對LINQ相當陌生,而且我正努力做出一個多JOIN。 所以,這是我的數據庫結構是怎樣的樣子:LINQ與一個左連接的多個連接
現在,應該如何查詢我的樣子,如果我有一個特定的等級,我想選擇 {Student.IndexNo,GradeValue.Value },但是如果對於特定等級和特定用戶沒有等級值,則應該返回null(左連接)?
我對LINQ相當陌生,而且我正努力做出一個多JOIN。 所以,這是我的數據庫結構是怎樣的樣子:LINQ與一個左連接的多個連接
現在,應該如何查詢我的樣子,如果我有一個特定的等級,我想選擇 {Student.IndexNo,GradeValue.Value },但是如果對於特定等級和特定用戶沒有等級值,則應該返回null(左連接)?
的手段來得到一個LEFT JOIN是使用DefaultIfEmpty()方法:
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;
故意張貼這在2015年的新手找對谷歌打的解決方案。我設法破解和編程我的方式進入解決方案。
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
};
主要生產以下SQL代碼內部
{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]
}
使用的導航性能,無需連接。 –