[英]LINQ Null Join with Pivot Table
我正在嘗試獲取可能或可能不屬於1個或多個組的服務器列表以在網格中顯示。
例
ServerID IP GroupID
1 192.168.1.44 1
1 192.168.1.44 10
2 192.168.1.45 1
3 192.168.1.46 2
4 192.168.1.47 null
5 192.168.1.48 null
如果我在GroupServer表中沒有記錄。 (由於沒有組或組存在但未分配)我希望得到這樣的結果:
ServerID IP GroupID
1 192.168.1.44 null
2 192.168.1.45 null
3 192.168.1.46 null
4 192.168.1.47 null
5 192.168.1.48 null
既然是多對多的關系。 我有
我找不到LINQ Pivot Table示例。 所以我試着建立自己的。
var query = (from sg in context.ServerGroups
join servers in context.Servers on sg.ServerID equals servers.ID
join groups in context.Groups on sg.GroupID equals groups.ID
into serverxgroup
from gAddrBilling in serverxgroup.DefaultIfEmpty()
select new
{
ServerID = sg.ServerID,
ServerIP = server.IP,
GroupID = sg.GroupID
});
上面的查詢沒有檢索任何東西我很安靜,不明白“來自gAddrBilling”是什么。 由於我修改了一個片段,我正在努力工作。 所以我想知道是否有人已經面臨這樣的問題,並給我一些提示,片段或關於我缺少什么的建議。
謝謝。
首先,這不是一個數據透視查詢,而是通過顯式聯結表對多對五關系進行常規查詢。
其次,看起來您正在使用Entity Framework,在這種情況下,您最好定義和使用導航屬性而不是手動join
。
第三,也是最重要的,查詢的結構是錯誤的。 如果您想獲得可能屬於或不屬於一個或多個組的服務器列表 ,那么您應該從Servers
開始查詢(記錄您希望始終包含的表,而不是從缺少某些ServerID
鏈接表) )然后使用左外連接 s到這樣的其他表:
var query =
from s in servers in context.Servers
join sg in context.ServerGroups on s.ID equals sg.ServerID
into s_sg from sg in s_sg.DefaultIfEmpty() // make the above LEFT OUTER JOIN
// You can remove the next two lines if all you need is the GroupId
// and keep them if you need some other Group field in the select
join g in context.Groups on sg.GroupID equals g.ID
into sg_g from g in sg_g.DefaultIfEmpty() // make the above LEFT OUTER JOIN
select new
{
ServerID = s.ID,
ServerIP = s.IP, // or sg.IP?
GroupID = (int?)sg.GroupID
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.