简体   繁体   English

按 linq 分组到实体查询,通过加入表获得一条具有最新时间戳的记录

[英]group by linq to entity query to get one record having latest timestamp by joining tables

There are two tables and using linq query to get records.有两个表并使用 linq 查询来获取记录。 From second table, there can be multiple rows corresponding to first table with date timestamp... based on below query, I am getting all records, but is there a way we can get the row from second table which has latest timestamp?从第二个表中,可以有多行对应于具有日期时间戳的第一个表...根据以下查询,我正在获取所有记录,但是有没有办法从第二个表中获取具有最新时间戳的行?

Table Parent

ID            Name    
1              M            
2              N             
3              O
4              P
5              Q

Table Child
Id            fkID        DateTime
1              2              01/12/2021 09:12:20
2              2              01/12/2021 09:13:20
3              2              01/12/2021 09:14:20
4              2              01/12/2021 09:15:20
5              2              01/12/2021 **09:16:20**

Linq query: Linq查询:

from p in Parent
join c in Child on p.id equals c.fkId into cJoin
from cJoin in cJoin.DefaultIfEmpty()
select new TempResponse
{
Id = p.Id,
Name = p.Name,
Date = c.Date
}

I am getting 10 records using above query but just need 5 records i.e. from child table instead of all 5 records, we need a record that has latest time stamp
 
**expected output**
1              M
2              N             01/12/2021 09:16:20 
this record is 5'th record from child table because this one has latest date time stamp 
( latest record )
3              O
4              P
5              Q

Is there any way we can use group by and get the record that has latest time stamp from second table?有什么方法可以使用 group by 并从第二个表中获取具有最新时间戳的记录?

Assuming you have defined navigation properties for the FK, I would use a query like;假设您已经为 FK 定义了导航属性,我会使用如下查询;

dbContext.Child.Where(c => c.Date == c.Parent.Child.Max(c2 => c2.Date))

I believe you can use:我相信你可以使用:

var ans = from p in Parent
          join cmax in (
            from c in Child
            group c by c.fkId into cg
            select cg.OrderByDescending(c => c.Date).FirstOrDefault())
          on p.Id equals cmax.fkId into cJoin
          from c in cJoin.DefaultIfEmpty()
          select new TempResponse {
              Id = p.Id,
              Name = p.Name,
              Date = c != null ? c.Date : null
          };

Note that the order of results seems to vary on SQL Server unless you add another orderby clause before the select to force an order.请注意,SQL 服务器上的结果顺序似乎有所不同,除非您在select之前添加另一个orderby子句以强制执行订单。

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

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