Linq查询具有多个group by和Scalar值函数

时间:2014-05-04 01:42:39

标签: c# sql linq entity-framework

我正在尝试编写LINQ查询,使用Entity Framework具有多个group by和标量值函数。

这是一个名称较简单的示例查询:

var test = context.<db_view>.Where(predicate)
                            .GroupBy(x => new {x.col1, x.col2, x.col3})
                            .Select(y => new
                                         {
                                             a = y.key.col1,
                                             b = y.key.col2,
                                             c = y.key.col3,
                                             d = ctx.ScalarFunction(y.key.col2)
                                         });

但是我收到了错误:

"Column Distinct1.col1 is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause."

我在GROUP BY子句中有col1。我在这里错过了什么吗?

这是Entity Framework生成的SQL查询:

SELECT 
    1 AS [C1], 
    [Distinct1].[col1] AS [col1], 
    [Distinct1].[col2] AS [col2], 
    [Distinct1].[col3] AS [col3], 
    [dbo].[scalarfunction]([Distinct1].[col2]) AS [C2], 
    FROM ( SELECT DISTINCT 
        [Extent1].[col1] AS [col1], 
        [Extent1].[col2] AS [col2], 
        [Extent1].[col3] AS [col3], 
        FROM (SELECT 
    [view].[col1] AS [col1], 
    [view].[col2] AS [col2], 
    [view].[col3] AS [col3], 
    [view].[col4] AS [col4], 
    [view].[col5] AS [col5], 
    [view].[col6] AS [col6] 

    FROM [dbo].[view] AS [view]) AS [Extent1]
        WHERE (predicate
    )  AS [Distinct1]

1 个答案:

答案 0 :(得分:0)

为什么要使用GroupBy?你不需要团体。你只需要(col1,col2 col3)不同的元组。 因此,请使用Distinct运算符。 试试这个:

var test = context.<db_view>.Where(predicate)
                        .Select(x => new {x.col1, x.col2, x.col3})
                        .Distinct()
                        .Select(y => new
                                     {
                                         a = y.col1,
                                         b = y.col2,
                                         c = y.col3,
                                         d = ctx.ScalarFunction(y.col2)
                                     });