【问题标题】:Entity Framework - Most recent record in the left join实体框架 - 左连接中的最新记录
【发布时间】:2016-07-28 21:48:33
【问题描述】:
我知道周围有很多类似的查询,但我想知道我们如何在实体框架中编写以下 SQL 查询,
select * from RequestDetail d
left join (select RequestDetailId, Max(RequestedOn) RequestedOn from RequestHistory group by RequestDetailId) as h
on h.RequestDetailId = d.Id
阅读了很多帖子,我找不到确切的副本。
【问题讨论】:
标签:
c#
sql
entity-framework
linq
linq-to-entities
【解决方案1】:
您可以在 Linq to Entities 中执行相同操作:
var innerquery=from e in RequestHistory
group e by e.RequestDetailId into g
select new {
RequestDetailId=g.Key,
RequestedOn =g.Max(r=>r.RequestedOn)
};
var query= from d in RequestDetail
join h in innerquery on d.Id equals h.RequestDetailId into gj
from e in gj.DefaultIfEmpty()
select new {d, e};
我首先创建了内部查询,以帮助您更好地了解如何执行此操作,但是您可以将两个查询合并为一个,但这没有任何区别。