Include会影响Count的性能吗?

时间:2017-09-14 12:22:28

标签: c# entity-framework

我使用C#Entity Framework并使用以下方法来计算我的学生

public static int GetStudentCount()
{
    using(SchoolContext ctx = new SchoolContext())
    {
        return  ctx.Student.Include("Subjects").Include("Subjects.SubjectsDescription").Include("Teacher").Count();
    }
}

问题: 这种方法有性能差异吗?

public static int GetStudentCount()
{
    using(SchoolContext ctx = new SchoolContext())
    {
        return ctx.Student.Count();
    }
}

更新:由于有些用户对为什么要添加Include()感兴趣 - 我想重用一个带有serval过滤器的方法。所以我有一种方法可以让所有学生GetStudent和一种方法使用相同的代码来过滤数据并只返回一个计数(用于数据库分页)

public static int GetStudentCount(Filter f)
{
   using(SchoolContext ctx = new SchoolContext())
   {
      return GetStudents(ctx.Student.AsQueryable(),f).Count(); // has filters an Include()
   }
}

1 个答案:

答案 0 :(得分:2)

测试差异我执行下面的代码并将生成查询记录到我的oracle数据库。

var context = new DbContext();
context.Database.Log = Log;
var count = context.TBCO_CATEGORY.Count();

生成查询

SELECT 
"GroupBy1"."A1" AS "C1"
FROM ( SELECT 
    COUNT(1) AS "A1"
    FROM "SIMS"."TBCO_CATEGORY" "Extent1"
)  "GroupBy1"

然后我执行以下代码

var context = new SIMSContext();
context.Database.Log = Log;
var count = context.TBCO_CATEGORY.Include(x=>x.TBCO_ITEM).Count();

生成SQL是:

SELECT 
"GroupBy1"."A1" AS "C1"
FROM ( SELECT 
    COUNT(1) AS "A1"
    FROM "SIMS"."TBCO_CATEGORY" "Extent1"
)  "GroupBy1"

表示相同的SQL语句,因此执行计划相同。