【问题标题】:Join with last record of details table加入明细表的最后一条记录
【发布时间】:2021-08-31 06:02:49
【问题描述】:

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

标题:

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

我想要带有相关 Last 详细记录的 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 无法识别方法 'Details.LastOrDefault()Details' 方法,并且此方法无法转换为存储表达式。

我怎样才能得到以上结果?

谢谢

【问题讨论】:

    标签: c# entity-framework linq linq-to-entities c#-7.0


    【解决方案1】:

    这个查询应该返回想要的结果:

    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
    }
    

    【讨论】:

    • 谢谢,但没用。它无法访问h in line:from d in Details.Where(d => d.HeaderId == h.Id)
    • 你应该有。常见的 SelectMany 查询和 h 标识符应该是可访问的。我之前做过数百个类似的查询。
    • 抱歉,我没有看到两个from。我去看看
    【解决方案2】:

    您应该将代码更改为:

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

    【讨论】:

      猜你喜欢
      • 2021-05-07
      • 1970-01-01
      • 2020-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-03
      相关资源
      最近更新 更多