LINQ Null加入数据透视表

时间:2016-09-20 17:15:29

标签: c# linq null left-join 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     

因为是多对多的关系。我有

  1. 组表
  2. 服务器表
  3. GroupServer表
  4. 我找不到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""来自gAddrBilling"是为了。由于我修改了一个片段,我正在努力工作。所以我想知道是否有人已经面临这样的问题并给我一些提示,片段或关于我失踪的内容的建议。

    谢谢。

1 个答案:

答案 0 :(得分:0)

首先,这不是一个数据透视查询,而是通过显式联结表对多对五关系进行常规查询。

其次,看起来您正在使用Entity Framework,在这种情况下,您最好定义并使用导航属性而不是手动join

第三,也是最重要的,查询的结构是错误的。如果您想获取可能属于或不属于一个或多个组的服务器列表,那么您应该从Servers开始查询(记录您希望始终的表)包括,而不是从缺少某些ServerID的链接表中),然后将left outer join 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
    };
相关问题