2017-04-26 261 views
1

我有兩個表,提交符號提交有單個條目和記號有多個條目通過AppID鏈接提交。Linq to Entities查詢 -

我試圖完成的是將提交的內容提交給定的日期範圍,並提交最新的符號。

我已經設法獲得所有的數據;然而,它是複製每個提交記錄爲每個符號提交。

這是我目前的代碼。任何人都可以幫我解決這個問題嗎?

var query = (from s in db.Submissions 
      from n in db.notations 
      from d in db.DCodes 
      where s.AppID == (int) n.AppID 
      && s.DCode == d.DCode1 
      && s.received >= dts 
      && s.received <= dte 
      select new ApplicationTrackingSystem.customModels.Export 
      { 
       AppID = s.AppID, 
       received = s.received, 
       //dcode = s.DCode, 
       dcode = d.description, 
       firstName = s.firstName, 
       middleName = s.middleName, 
       lastName = s.lastName, 
       street = s.street, 
       city = s.city, 
       state = s.state, 
       zip = s.zip, 
       position = s.position, 
       hearAbout = s.hearAbout, 
       referredby = s.referredBy, 
       email = s.email, 
       commentID = n.commentID, 
       commentDate = n.commentDate, 
       user = n.userID, 
       comment = n.comment 
      }).ToList(); 
+0

它如何只選擇「最近的」符號? –

回答

2

嘗試沿着這些方向行事。 集團通過提交記號,然後只檢索第一順序由commentDate下降

var result = from s in db.Submissions 
      join n in db.notations on s.AppID equals n.AppID 
      where s.received >= dts && s.received <= dte 
      group n by s into g 
      let recentNotation = g.OrderDescendingBy(item => item.commentDate).First() 
      select new ApplicationTrackingSystem.customModels.Export { 
       AppID = g.Key.AppId, 
       /* rest of s fields */, 
       commentID = recentNotation.commentID, 
       commentDate = recentNotation.commentDate, 
       user = recentNotation.userID, 
       comment = recentNotation.comment 
      }; 

伊凡糾正我,這是更好的使用GroupJoin代替:

var result = from s in db.Submissions 
      join n in db.notations on s.AppID equals n.AppID into g 
      from n in g.OrderDescendingBy(item => item.commentDate).First() 
      where s.received >= dts && s.received <= dte 
      select new ApplicationTrackingSystem.customModels.Export { 
       AppID = g.Key.AppId, 
       /* rest of s fields */, 
       commentID = n.commentID, 
       commentDate = n.commentDate, 
       user = n.userID, 
       comment = n.comment 
      }; 
+0

'GroupBy',真的嗎?重新創建'GroupJoin' :) –

+0

@IvanStoev - 謝謝:)修正 –

+0

@GiladGreen非常感謝。我一直在爲此工作了幾個小時。我注意到的一件事是我失去了第三個表的參考。 「從db.DCode中的d」我將如何去添加第三個表到這個解決方案? –