【问题标题】:Linq query with two joins on inner select in EF在 EF 中的内部选择上有两个连接的 Linq 查询
【发布时间】:2012-04-28 00:38:39
【问题描述】:

我正在尝试为 EF 创建一个 Linq 查询,该查询连接来自内部选择的 2 个值。在下面,您会发现可以解决问题的 SQL 查询,而在 Linq 中尝试这样做会更加棘手。

我使用 POCO 对象并希望查询返回 List 而不是匿名类型。 Linq to EF 可以做到这一点吗?

选择 s1.* FROM [统计] s1 内部联接 ( 选择 MAX(CreateDate) 作为 createdate 来自[统计] 按用户 ID 分组 ) s2 ON s1.UserId = s2.[UserId] 和 s1.CreateDate = s2.createdate ORDER BY s1.Balance desc

【问题讨论】:

  • 此 SQL 无效,因为 s2 只有聚合、创建日期,并且没有 UserId 列。修复:SELECT s1.* FROM [Statistics] s1 INNER JOIN (SELECT UserId, MAX(CreateDate) as createdate FROM [Statistics] GROUP BY UserId) s2 ON s1.UserId = s2.UserId and s1.CreateDate = s2.createdate ORDER BY s1.余额说明

标签: linq entity-framework


【解决方案1】:

您可以使用 Where 或 Join 来做到这一点。

from s1 in Statistics
join s2 in (from s in Statistics group s by s.UserId into g
select new { UserId = g.Key, CreateDate = g.Max (s => s.CreateDate) })
on new { s1.UserId, s1.CreateDate } equals new { s2.UserId, s2.CreateDate }
orderby s1.Balance descending
select s1;

或者,

from s1 in Statistics
from s2 in (from s in Statistics group s by s.UserId into g
select new { UserId = g.Key, CreateDate = g.Max (s => s.CreateDate) })
where s1.UserId == s2.UserId && s1.CreateDate == s2.CreateDate
orderby s1.Balance descending
select s1;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-27
    • 1970-01-01
    • 2019-03-27
    • 2013-12-16
    • 1970-01-01
    相关资源
    最近更新 更多