实体框架6 - 重用选择查询

时间:2014-11-03 11:08:08

标签: .net sql-server entity-framework

我正在使用.net和Entity Framework 6

我在SQL Server中有一个表Activities,它有一个ExerciseType

我正在尝试计算每种运动类型的总行数。

//dbCtx is of type System.Data.Entity.DbContext 
int nbType1 = dbCtx.Activities.Count(a => a.Exercise == "TYPE1");
int nbType2 = dbCtx.Activities.Count(a => a.Exercise == "TYPE2");
int nbType3 = dbCtx.Activities.Count(a => a.Exercise == "TYPE3");
int nbType4 = dbCtx.Activities.Count(a => a.Exercise == "TYPE4");

这些是与前一代码对应的查询:

SELECT 
    [GroupBy1].[A1] AS [C1]
    FROM ( SELECT 
        COUNT(1) AS [A1]
        FROM [dbo].[Activities] AS [Extent1]
        WHERE (N'TYPE1' = [Extent1].[ExerciseType])
    )  AS [GroupBy1]

SELECT 
    [GroupBy1].[A1] AS [C1]
    FROM ( SELECT 
        COUNT(1) AS [A1]
        FROM [dbo].[Activities] AS [Extent1]
        WHERE (N'TYPE2' = [Extent1].[ExerciseType])
    )  AS [GroupBy1]

SELECT 
    [GroupBy1].[A1] AS [C1]
    FROM ( SELECT 
        COUNT(1) AS [A1]
        FROM [dbo].[Activities] AS [Extent1]
        WHERE (N'TYPE3' = [Extent1].[ExerciseType])
    )  AS [GroupBy1]

SELECT 
    [GroupBy1].[A1] AS [C1]
    FROM ( SELECT 
        COUNT(1) AS [A1]
        FROM [dbo].[Activities] AS [Extent1]
        WHERE (N'TYPE4' = [Extent1].[ExerciseType])
    )  AS [GroupBy1]

查询很慢。

因为每次调用EF的查询几乎相同。

是否有可能通过缓存查询来提高性能?

1 个答案:

答案 0 :(得分:1)

只需在单个查询中执行此操作,然后在返回的数据集中提取值。

所以在SQL中你会这样做:

SELECT ExerciseType, COUNT(ExerciseType) as ETCount 
FROM Activities 
GROUP BY ExerciseType

因此,通过取消where子句并添加分组,您将返回按练习类型分组的计数。

在EF中,它看起来应该是这样的:

var results = dbCtx.Activities 
                   .GroupBy(a => a.Exercise)
                   .Select(a => new { ExerciseType = a.Key, ETCount = a.Count() });

输出类似于:

Exercise | ETCount
------------------
TYPE1    | 3
TYPE2    | 9
TYPE3    | 6
TYPE4    | 12