簡體   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