从每个组中选择单个元素,其中包含最大DateTime值

时间:2018-05-17 09:30:23

标签: linq entity-framework-core ef-core-2.0

模特:

public class ReferenceParameterHistory
{
    [Key]
    public int IDReferenceParameterHistory { get; set; }
    public double Value { get; set; }
    public string Value_S { get; set; }
    public DateTimeOffset CreatedAt { get; set; }
    [Required]
    public bool IsStable { get; set; }

    public int? IDReference { get; set; }
    public Reference Reference { get; set; }

    [Required]
    public int IDParameterTemplate { get; set; }
    public ParameterTemplate ParameterTemplate { get; set; }
}

我在ASP.NET核心控制器中的代码:

            [HttpGet]
    public async Task<IActionResult> GetReferenceParameterHistory(int? IDparameterTemplate,
                                                                  int? IDreference,
                                                                  DateTimeOffset? startDate,
                                                                  DateTimeOffset? endDate,
                                                                  bool latestOnly)
    {
        try
        {
            IQueryable<ReferenceParameterHistory> query = _context.ReferenceParameterHistory.OrderByDescending(rph => rph.IDReferenceParameterHistory);
            if (IDparameterTemplate != null && IDparameterTemplate > 0)
                query = query.Where(rph => rph.IDParameterTemplate == IDparameterTemplate);
            if (IDreference != null && IDreference > 0)
                query = query.Where(rph => rph.IDReference == IDreference);
            if (startDate != null)
                query = query.Where(rph=> rph.CreatedAt >= startDate);
            if (endDate != null)
                query = query.Where(rph => rph.CreatedAt <= endDate);
            if (latestOnly)
            {
                // I tried this but it doesnt compile and I don't have idea how to solve this ....

                //query = (from rph in query
                //         group rph by rph.IDParameterTemplate
                //            into groups
                //            where groups.Max(rph => rph.CreatedAt)
                //         select groups.Key);
            }


            var referenceParameterHistory = await query.AsNoTracking().ToListAsync();
            if (referenceParameterHistory.Any())
                return new ObjectResult(referenceParameterHistory);

            return new NotFoundResult();
        }
        catch (Exception ex)
        {
            _logger.LogError(ex.Message);
            return new StatusCodeResult(500);
        }
    }

我有一个基于ReferenceParameterHistory模型类的数据库表。我希望将IDParameterTemplate从该表中提取的记录分组,并从每个组中提取我需要提取CreatedAt列中最高值的记录(最新记录)。因此,每个组都包含许多recods,但我只需要在CreatedAt列中获取最大值。结果应为IEnumerable ReferenceParameterHistory,因为我将该查询存储在IQueryable变量中,然后将其发送到SQL Server以处理查询。我的例子中的注释代码正是我尝试的但我不知道该怎么做。

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

你在lambda中重用了变量rph。

How to select only the records with the highest date in LINQ

  

query =(来自查询中的rph
             将rph.IDParameterTemplate分组为r
             选择g.OrderByDescending(t =&gt; t.CreatedAt).FirstOrDefault());