1

我有三个实体:组、活动和评论。每个实体在数据库中都表示为一个表。一个组有很多活动,一个活动有很多评论。每个实体都有一个 CreatedDate 字段。我需要查询所有组+在该组的对象图上创建的最新实体的 CreatedDate。

我已经构建了一个 sql 查询,它可以满足我的需求,但我不确定如何在实体框架中执行此操作。特别是这一行:(SELECT MAX(X) FROM (VALUES (g.CreatedDate), (a.CreatedDate), (c.CreatedDate))提前感谢您的帮助。这是完整的查询:

WITH GroupWithLastActivityDate AS (
    SELECT DISTINCT  
        g.Id
        ,g.GroupName
        ,g.GroupDescription
        ,g.CreatedDate              
        ,g.ApartmentComplexId
        ,(SELECT MAX(X)
            FROM (VALUES (g.CreatedDate), (a.CreatedDate), (c.CreatedDate)) AS AllDates(X)) AS LastActivityDate
    FROM Groups g
    LEFT OUTER JOIN Activities a
        on g.Id = a.GroupId
    LEFT OUTER JOIN Comments c
        on a.Id = c.ActivityId  
    WHERE g.IsActive = 1
)
SELECT 
    GroupId = g.Id
    ,g.GroupName
    ,g.GroupDescription             
    ,g.ApartmentComplexId
    ,NumberOfActivities = COUNT(DISTINCT a.Id)
    ,g.CreatedDate      
    ,LastActivityDate = Max(g.LastActivityDate)     
FROM GroupWithLastActivityDate g
INNER JOIN Activities a
    on g.Id = a.GroupId
WHERE a.IsActive = 1
GROUP BY  g.Id
        ,g.GroupName
        ,g.GroupDescription
        ,g.CreatedDate
        ,g.ApartmentComplexId

我应该补充一点,现在我已经用这个查询(加上其他一些东西)构建了一个视图,我正在用一个 SqlQuery 进行查询。

4

0 回答 0