Select 几个级别的孩子

Select several levels of childs

我正在使用 entity Framework 6。 在我的数据库中,我有这些表:

MasterTable ( Id , name)
    Child1 ( ID , name , vl1 , Master_ID)
    Child2 ( ID , name , vl2 , MasterID )
    Child3 (ID , name , vl3 , Master_ID )
        Child3Itm ( ID , name , Child3_ID)

对于给定的 MasterTable 项,我想从数据库中加载单个查询:

并在每个 Child3 中加载所有 Child3Itm 内容。

我正在使用这个查询:

Dim lst = (From t In context.MasterTable.Where(Function(t1) t1.id = 7)
                 Select New With {
                                   t,
                                   .chld1 = t.child1s.Where(Function(t21) t21.vl1 >5),
                                   .chld2 = t.child2s.Where(Function(t31) t31.vl2>6 ),
                                   .chld3 = t.child3s.Where(Function(t41) t41.vl3>7).Select(Function(t411) t411.Child3Itms)
                                  }).ToList

问题是没有选择 Child3。其他都OK。我能做什么?提前致谢!

如果没有看到您的数据,将很难进行诊断。但由于您可以访问调试器,因此您可以自己完成。使用下面的代码,跨过每一行并检查变量。应该很容易看出您的代码哪里出错了

Dim masters = From t In context.MasterTable Where t = 7
Dim child1s = From m In masters Where m.child1s.vl1 > 5
Dim child2s = From m In masters Where m.child2s.vl2 > 6
Dim child3s = From m In masters Where m.child3s.vl3 > 7
Dim child3i = child3s.Child3Itms

您的问题可能有错字。确保 child3s 的条件正确:

t41.vl>7

应该是这个吧?

t41.vl3 > 7
Dim lst = (From t In context.MasterTable.Where(Function(t1) t1.id = 7)
             Select New With {
                               t,
                               .chld1 = t.child1s.Where(Function(t21) t21.vl1 >5),
                               .chld2 = t.child2s.Where(Function(t31) t31.vl2>6 ),
                               .chld3 = t.child3s.Where(Function(t41) t41.vl3>7),
                               .chld3itms = t.child3s.Where(Function(t51) t51.vl3>7).Select(Function(t511) t511.Child3Itms)
                              }).ToList
Dim lst = (From t In context.MasterTable.Where(Function(t1) t1.id = 7)
              Select New With {
                           t,
                           .chld1 = t.child1s.Where(Function(t21) t21.vl1 >5),
                           .chld2 = t.child2s.Where(Function(t31) t31.vl2>6 ),
                           .chld3 = (From t2 in t.child3s.Where(Function(t41) t41.vl3>7) 
                                Select New With {
                                           t2,
                                           .chld3it=t2.Child3Itms   
                                                 })
                               }).ToList

这也行得通。 如果有人能告诉我这个答案与 antoni 发布的其他解决方案相比是否更好???