Get max & min from Entity Framework, in one query and with best query possible

前端 未结 2 1590
你的背包
你的背包 2021-01-17 11:37

I\'m aware of this question, but what I would like to do is obtain something close to this generated SQL:

select MAX(C         


        
相关标签:
2条回答
  • 2021-01-17 12:25

    Try removing the let statements - the below produces expected results:

    var q = from d in db.Table
            where d.Id == 1
            group d by d.Id into g
            select new
            {
                Id = g.Key, // shown for illustrative purposes
                ColumnMin = g.Min( gi => gi.Column ),
                ColumnMax = g.Max( gi => gi.Column )
            };
    
    var result = q.SingleOrDefault();
    

    Resulting SQL:

    SELECT 
        [GroupBy1].[K1] AS [Id],
        [GroupBy1].[A1] AS [C1], 
        [GroupBy1].[A2] AS [C2]
        FROM ( SELECT 
            [Extent1].[Id] AS [K1], 
            MIN([Extent1].[Column]) AS [A1], 
            MAX([Extent1].[Column]) AS [A2]
            FROM [dbo].[Table] AS [Extent1]
            WHERE 1 = [Extent1].[Id]
            GROUP BY [Extent1].[Id]
        )  AS [GroupBy1]
    
    0 讨论(0)
  • 2021-01-17 12:25
    var query = from d in db.Table
                where d.Id == 1
                select
                {     
                    d.Max(t =>t.yourColName),  
                    d.Min(t =>t.yourColName)  
                };
    
    0 讨论(0)
提交回复
热议问题