繁体   English   中英

在没有PK FK的情况下与Lambda进行左联接以获得父子结果

[英]Doing a left join with Lambda for parent/child results without PK FK

我需要从两个具有未定义的父子关系的表中返回结果:父表具有一个LinkTypeId和LinkId字段,用于确定每行引用哪个子表。
因此,父行x可能指向Child1,Child2甚至是Child3表。

由于结果与实体框架一起使用,该实体框架仅包含可为空的子对象的ID字段,因此我应该能够获得也填充了可为空的子项的父项的结果。 我们将基于EF的结果映射到反映将要使用的对象的类。

我得到了以下查询,但由于它是在LinqPad中构建的,因此未使用EF,并且返回了两个记录集。 如何使孩子与父母建立联系?

var qry = Parent.GroupJoin(
          ChildItem, 
          dl => dl.LinkId,
          itm => itm.ChildItemId,
          (x,y) => new { Parent = x, ChildItem = y })
    .Where( x => x.Parent.PKId == 123 && x.Parent.LinkTypeId == 1 )
    .SelectMany(
          x => x.ChildItem.DefaultIfEmpty(),
          (x,y) => new { Parent=x.Parent, ChildItem=y}) ;

          qry.Dump();

编辑:
该查询返回结果以及正确的数据,但是返回填充了Parent.Child对象的Generic List<{Parent, ChildItem}> 而不是 IEnumerable<Parent>

我得到了同事的帮助:确实很简单:我应该只在Query语句之后加入ChildItems。

            var qry= dataContext.Parent
                   .GroupJoin(
                      dataContext.ChildItems,
                      dl => dl.LinkId,
                      itm => (Int32?)(itm.ChildItemId),
                      (x, y) =>
                         new
                         {
                             Parent = x,
                             ChildItems = y
                         }
                   )
                   .Where(x => (((x.Parent.ParentId == 1)) 
                       && (x.Parent.LinkTypeId == 1)
                   )
                   .SelectMany(
                      x => x.ChildItems.DefaultIfEmpty(),
                      (x,y) => new { Parent=x.Parent, ChildItems=y});

            var tmpResult = result.ToList();

            foreach (var line in tmpResult)
            {
                line.Parent.Item = line.ChildItems;
            }

            return tmpResult.Select(a => a.Parent).ToList();

感谢所有尝试帮助的人!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM