2013-04-04 57 views
2

计,我有以下表结构:的LINQ到SQL选择项目与嵌套

enter image description here

使用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 
} 

BUT ,我希望这些东西按照与每个E相关联的A的数量排序。我一直在尝试使用join/orderby和嵌套查询的组合,米不知道如何得到它。

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

enter image description here

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

不过是要做出参考打破某种DB规范化规则?

回答

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() 
} 

另一种方式来做到这一点可能是先从A S和他们组是这样的:

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() 
} 
+0

很好的答案!使用你的第三个例子,我可以很容易地根据特定的B进行过滤。 – 2013-04-04 15:09:25

+1

@MikeCaron很乐意帮助:) – 2013-04-04 15:19:44

1

那么,一直跟随你的实体关系吧:

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。
再次,SelectMany(c => c.As)给你所有的通过Cs和Ds你的电子。

+1

你的回答也很好,但我选择了@ p.s.w.g,因为他提供了更多的方法来解决它。 – 2013-04-04 15:10:14