简体   繁体   English

实体框架查询以从表中获取最新版本

[英]Entity Framework query to fetch the latest version from table

I Have this table in my DB:我的数据库中有这张表:

   Id  Name    Version    AddedDate
   1   Table    1         2020-02-26 15:25:04.5366703
   2   Table    1         2020-02-26 15:25:01.8502928
   3   Table    2         2020-02-26 15:18:09.0415632
   4   Table    2         2020-02-26 15:18:23.6646620
   5   Chair    1         2020-02-26 15:16:25.7518968
   6   Chair    1         2020-02-26 15:18:49.1826797
   7   Chair    2         2020-02-26 15:24:41.0905596
   8   Chair    2         2020-02-26 15:24:37.4333049

I have tried this SQL query and it works partially, but i need the entire row including the id and it fails if i add the Id to the select.我已经尝试过这个 SQL 查询,它部分工作,但我需要包括 id 的整行,如果我将 Id 添加到选择中,它会失败。

I need to write an entity framework query such that the result has the last added Table 1, Table 2, Chair 1, Chair 2我需要编写一个实体框架查询,以便结果具有最后添加的表 1、表 2、椅子 1、椅子 2

SELECT [Name],[Version], MAX(AddedDate) as AddedDate
From JsonSchemas
GROUP BY Name, Version
ORDER BY MAX(AddedDate) DESC

You can group on Name and version and get recent AddedDate by ordering on AddedDate as shown below:您可以按名称和版本进行分组,并通过按添加日期排序来获取最近的添加日期,如下所示:

var lst = dbContext.JsonSchemas.GetAsNoTracking()
                .GroupBy(a => new {a.Name, a.Version})
                //.ToList()
                .Select(g => g.OrderByDescending(t => t.AddedDate).FirstOrDefault())
                .ToList();

You could try this code :你可以试试这个代码:

var result = (from item in _dbContext.JsonSchemas.ToList()
                 group item by new { item.Name, item.Version } into r
                 select new
                 {
                     Id = r.Select(q => q.Id).First(),
                     Name = r.Key.Name,
                     Version = r.Key.Version,
                     AddedDate = r.Max(q => q.AddedDate)
                 }).ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM