2016-08-02 51 views
1

我有幾張桌子,主要是DefectRecord,其他叫做DefectArea,DefectLevel ......等,還有一個叫DefectAttachment。而這個問題是關於加入DefectRecord與其他表來獲得ViewModel進一步使用。我面臨的難題是關於DefectAttachment表格。如何在LINQ中使用額外的過濾功能執行左連接?

DefectRecordDefectAttachment有一對多的關係。儘管一個缺陷記錄可能沒有附件,但可能有多個附件。

按道理我試圖執行一個左連接中DefectRecord & DefectAttachment,但有一個更requiredment:

  • 如果有多個附件,只選擇最老的(即 一個與最古老的CreatedDate場值)

我被困在這個要求,我怎麼能用LINQ-to-Entities執行此操作?下面是什麼,我現在有代碼:

var ret = (from dr in defectRecordQuery 
      join ft in filterQuery on dr.FilterID equals ft.FilterID 
      join l in levelQuery on dr.LevelID equals l.LevelID 
      join a in attachmentQuery on dr.DefectRecordID equals a.DefectRecordID into drd 
      from g in drd.DefaultIfEmpty() 
      select new DefectRecordViewModel 
      { 
       DefectRecordCode = dr.Code, 
       DefectAttachmentContent = g == null ? null : g.FileContent, 
       LookupFilterName = ft.FilterName, 
      }).ToList(); 

的*查詢變量是IQueryable對象,獲得相應的表的完整列表。

+2

在drd.DefaultIfEmpty()'從克更改''到從drd.DefaultIfEmpty()克OrderByDescending(A => a.CreatedDate)。取(1)'應足以 –

+0

@IvanStoev - 約在'select'部分改變它並添加'Take(1)',但沒有想到它'DefaultIfEmpty()'。尼斯 –

回答

1

組的結果由CodeFilterName,然後對內容採取具有最早的日期

var ret = (from dr in defectRecordQuery 
      join ft in filterQuery on dr.FilterID equals ft.FilterID 
      join l in levelQuery on dr.LevelID equals l.LevelID 

      join d in attachmentQuery on dr.DefectRecordID equals d.DefectRecordID into drd 
      from g in drd.DefaultIfEmpty() 
      group g by new { dr.Code, ft.FilterName } into gg 

      select new DefectRecordViewModel 
      { 
       DefectRecordCode = gg.Key.Code, 
       DefectAttachmentContent = gg.OrderByDescending(x => x.CreateDateTime).FirstOrDefault() == null? null: gg.OrderByDescending(x => x.CreateDateTime).FirstOrDefault().FileContent, 
       LookupFilterName = gg.Key.FilterName, 
      }).ToList(); 

如果使用C#6.0或更高版本,那麼你可以做的組中的項目:

DefectAttachmentContent = gg.OrderByDescending(x => x.CreateDateTime) 
          .FirstOrDefault()?.FileContent, 
+0

作品就像一個魅力,謝謝.. – shole

+0

@shole - 哦很棒:)害怕它贏了'因爲不能真的測試它:) –

+0

確實改變了你的代碼了一點,但那給了我一個正確的方向:)! – shole