Search code examples
c#linqt-sqlentity-framework-6

Converting SQL to LINQ with Min and Max functions


I have the following SQL snippet that I am trying to convert to a LINQ query as part of a more complex query but I cannot see how to get started:

SELECT
    AT.PrimaryIDChanged AS PID,
    MAX(AT.ProcessID) AS EventTypeID,
    MIN(AT.AuditDateTime) AS EventDate
FROM
    dbo.AuditTrail AS AT    
WHERE
    AT.AuditTargetTableID = 13
    AND AT.ProcessID IN (30, 31)
GROUP BY
    AT.PrimaryIDChanged 

Target is EF6. I have no code to share as yet


Solution

  • You can do it in Query Syntax like this:

    var data =
        from at in context.AuditTrail
        where at.AuditTargetTableID == 13
           && new[]{ 30, 13 }.Contains(at.ProcessID)
        group at by at.PrimaryIDChanged into g
        select new {
            PID = g.Key,
            EventTypeID = g.Max(at => at.ProcessID),
            EventDate = g.Min(at => at.AuditDateTime),
        };
    

    Note the into g, this allows you to do multiple aggregation functions on the whole group.