Get Distinct Entries Based On Specific Column in Entity Framework

后端 未结 3 1203
暖寄归人
暖寄归人 2021-01-28 10:55

I have a SQLite table that contains every test result we\'ve run, and I\'m looking to write an entity framework query that returns only the most recent test result per project.

3条回答
  •  心在旅途
    2021-01-28 11:39

    While this isn't portable, here's how this can be done using SQLite-compatable SQL and Entity Framework:

    results = await _context.Results
        .FromSqlRaw("SELECT Results.* FROM (SELECT Id, ProjectId, MAX(Updated) as Updated " +
        "FROM Results GROUP BY ProjectId) as latest_results " +
        "INNER JOIN Results ON Results.Id = latest_results.Id")
        .Include(x => x.Project) //not required for question but useful
        .OrderBy(x => x.Project.Name)
        .AsNoTracking()
        .ToListAsync();
    

    If someone has a way to do this in pure LINQ/EF, but still perform the query server-side, I'll happily mark that as the answer, since this is dependent on the exact SQL dialect used.

提交回复
热议问题