【问题标题】:Linq to Sql selection of items with count of nestedLinq to Sql 选择具有嵌套计数的项目
【发布时间】:2013-04-04 14:48:53
【问题描述】:

我的表结构如下:

使用 Linq To SQL 我想得到一个这样的列表:

new {
    E = e,      // the E object
    Ds = e.Ds,  // list of D objects referenced by E
    NumAs = ??? // COUNT OF A objects that are eventually associated with this E
}

但是,我希望这些东西按与每个 E 关联的 A 的数量排序。

我一直在尝试结合使用 joins/orderby 和嵌套查询,但我不知道如何获得它。

如果我从表 E 到 A 的引用,那么这似乎是微不足道的; IE。这个:

from e in ctx.E
orderby e.As.Count()
select new {
   E     = e,
   Ds    = e.Ds,
   numAs = e.As.Count()
} 

但该引用是否违反了某种 DB 规范化规则?

【问题讨论】:

    标签: c# .net linq linq-to-sql


    【解决方案1】:

    你可以这样做

    from e in ctx.E
    let ds = e.Ds
    let cs = ds.SelectMany(d => d.Cs)
    let as = cs.SelectMany(c => c.As)
    orderby as.Count()
    select new {
       E     = e,
       Ds    = e.Ds,
       numAs = as.Count()
    } 
    

    或者这个,为了简洁

    from e in ctx.E
    let as = e.Ds.SelectMany(d => d.Cs).SelectMany(c => c.As)
    orderby as.Count()
    select new {
       E     = e,
       Ds    = e.Ds,
       numAs = as.Count()
    } 
    

    另一种方法可能是从As 开始并将它们分组如下:

    from a in ctx.A
    group a by a.C.D.E into g
    orderby g.Count()
    select new {
        E = g.Key,
        Ds = g.Key.Ds,
        numAs = g.Count()
    }
    

    【讨论】:

    • 很好的答案!使用您的第三个示例,我可以轻松地根据特定的 B 进行过滤。
    • @MikeCaron 很高兴为您提供帮助 :)
    【解决方案2】:

    好吧,请始终遵循您的实体关系:

    ctx.E.Select(e => new {
                     E = e
                   , Ds = e.Ds
                   , numAs = e.Ds.SelectMany(d => d.Cs).SelectMany(c => c.As).Count()
                     }
                 )
         .OrderBy(e => e.numAs);
    

    e.Ds.SelectMany(d=>d.Cs) 通过 Ds 为您提供与您的 e 相关联的所有 Cs。
    同样,SelectMany(c => c.As) 通过 Cs 和 Ds 为您提供与您的 e 相关联的所有 As。

    【讨论】:

    • 你的回答也不错,但我选择了@p.s.w.g,因为他提供了更多的方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-27
    • 1970-01-01
    相关资源
    最近更新 更多