LINQ加入以获得第二张桌子的最新记录

时间:2012-07-22 19:57:17

标签: c# asp.net linq

问题:

他们是两个表TableEmails和TableSentEmailRecords。因此,当发送电子邮件时,TableSentEmailRecords中会存储记录,例如发送时间等。

我想做一个LINQ查询,它从TableSentEmailRecords中获取TableEmails PLUS列的“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表中获取该特定电子邮件的最新记录。

任何想法???

3 个答案:

答案 0 :(得分: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)
            };

答案 1 :(得分:1)

我认为在这种情况下GroupJoin是正确的方法。使用子查询将起作用,但它不会那么有效。对不起,我不太了解更简单的查询语法,特别是我不知道如何使用它进行组连接。也许有人可以翻译。

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();

答案 2 :(得分: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();