2012-07-22 101 views
2

問題:LINQ加入從第二張表中獲取最新記錄

他們是兩張表TableEmails和TableSentEmailRecords。因此,當發送電子郵件時,諸如發送時間等的記錄存儲在TableSentEmailRecords中。

我想要做一個LINQ查詢,它使TableEmails的列加上TableSentEmailRecords中的「SentDate」列,顯示電子郵件發出的最新日期。

我嘗試這樣做:

List<CustomEmail> emails = new List<CustomEmail>(); 

var query = from c in db.TableEmails 
      join o in db.TableSentEmailRecords on c.EmailId equals o.EmailId 
         select new CustomEmail 
         { 
          EmailName = c.EmailName, 
          EmailId= c.EmailId, 
          EmailDescription = c.EmailDescription, 
          LastDateEmailSentOut = o.SentDate 
         }; 

emails = query.ToList(); 

但這不一定得到TableSentEmailRecords表中特定電子郵件的最新記錄。

任何想法?

回答

0

你可以嘗試這樣的事:

var query = (from c in db.TableEmails 
      join o in db.TableSentEmailRecordson c.EmailId equals o.EmailId 
      select new CustomEmail 
      { 
       EmailName = c.EmailName, 
       EmailId = c.EmailId, 
       EmailDescription = c.EmailDescription, 
       LastDateEmailSentOut = o.SentDate 
      }).OrderByDescending(c => c.LastDateEmailSentOut).ToList(); 
2

你可以只使用一個嵌套查詢,而不是加入:

var query = from c in db.TableEmails 
      select new CustomEmail 
      { 
       EmailName = c.EmailName, 
       EmailId= c.EmailId, 
       EmailDescription= c.EmailDescription, 
       LastDateEmailSentOut = db.TableSentEmailRecordson 
             .Where(x => x.EmailId = c.EmailId) 
             .Max(x => x.SentDate) 
      }; 
+0

感謝...看起來像這可能工作...只是另一點(對不起,我忘了在問題提)...相同的(最大)記錄其日期我將用作LastDateEmailSentOut,我想使用該記錄其他值來填充我的查詢中的其他幾個屬性。我可以那樣做嗎? – 2012-07-22 23:35:29

+0

@aDev我在回答中添加了關於此的詳細信息。 – MikeKulls 2012-07-23 22:25:14

1

我覺得羣組加入是在這種情況下,正確的方法。使用子查詢將起作用,但效率不會很高。對不起,我不知道更簡單的查詢語法,特別是我不知道如何執行組加入。也許有人可以翻譯。

db.TableEmails.GroupJoin(db.TableSendEmailRecordson, 
    o => o.EmailID, 
    i => i.EmailID, 
    (o, i) => new 
    { 
    EmailName = c.EmailName, 
    EmailId= c.EmailId, 
    EmailDescription= c.EmailDescription, 
    LastDateEmailSentOut = i.Max(x => x.SentDate) 
    }) 

要獲得所有從TableSendEmailRecordson你可以做這樣的事情的細節:

db.TableEmails.GroupJoin(db.TableSendEmailRecordson, 
    o => o.EmailID, 
    i => i.EmailID, 
    (o, i) => new 
    { 
    EmailName = c.EmailName, 
    EmailId= c.EmailId, 
    EmailDescription = c.EmailDescription, 
    LastSendEmailRecordson = i.FirstOrDefault(y => y.SentDate == i.Max(x => x.SentDate)) 
    }) 

這可能會抱怨被翻譯成SQL,如果是這樣的話,那麼您需要首先獲取數據然後用結果查詢,如

var emails = db.TableEmails.ToArray(); 
var emailSend = db.TableSendEmailRecordson.ToArray();