加入最后一条详细记录 table

Join with last record of details table

请考虑我数据库中的这两个表:

Header:

Id                   Name
-------------------------------
1                     London
2                     Berlin
3                     Paris

及详情:

Id          HeaderId            Amount           YearMonth
--------------------------------------------------------------------
1              1                 1000             2010-01
2              1                 2000             2010-05
3              2                 3000             2015-04
4              2                 2700             2017-12
5              2                 4500             2016-10
6              2                 7000             2011-09
7              1                 3000             2009-05

我想要 Header 条记录以及相关的 最后一条 条详细记录。例如:

HeaderId              HeaderName           Amount                     
----------------------------------------------------
1                       London              2000              
2                       Berlin              2700             
3                       Paris               Null             

我为 Inner Join 版本编写了此查询(但我想要 Outer Join 版本):

from h in Header
join d in Details
 on h.Id equals d.HeaderId
select new
{
        HeaderId = h.Id,
        HeaderName = h.Name,
        Amount = (Details.Where(k=>k.HeaderId == h.Id).OrderBy(m=>m.YearMonth).LastOrDefault() == null ? null : Details.Where(k=>k.HeaderId == h.Id).OrderBy(m=>m.YearMonth).LastOrDefault().Amount,
}

我得到了这个错误:

System.NotSupportedException: LINQ to Entities does not recognize the method 'Details.LastOrDefault()Details' method, and this method cannot be translated into a store expression.

如何获得以上结果?

谢谢

您应该将代码更改为:

 Amount = Details.Where(k=>k.HeaderId == h.Id).OrderByDescending(m => m.YearMonth).FirstOrDefault(o=>o.Amount);

此查询应该return 期望的结果:

from h in Header
from d in Details.Where(d => d.HeaderId == h.Id)
    .OrderByDescending(d => d.YearMonth)
    .Take(1)
    .DefaultIfEmpty()
select new
{
    HeaderId = h.Id,
    HeaderName = h.Name,
    Amount = d.Amount
}