【问题标题】:Get rowcount of large table using Entity framework使用实体框架获取大表的行数
【发布时间】:2016-09-28 13:24:16
【问题描述】:

我正在使用实体框架来获取包含数百万条记录的表的简单行数,并且我不需要任何 where 子句。 我尝试使用 Count 方法,但获取计数需要很长时间。有没有什么有效的方法可以在等待这么长时间的情况下获取计数?

【问题讨论】:

  • 你有示例代码吗?如果您使用Count()IEnumerable 版本,您的应用程序将检索所有行,然后对它们进行计数。如果您使用的是IQueryable 版本的Count(),那么数据库服务器会进行计数并且应该很快
  • 你能显示你的代码吗?
  • 只需对数据库执行原始 SQL 查询。这可能是实现这一目标的最快方法。 msdn.microsoft.com/en-us/data/jj592907.aspx

标签: c# sql-server entity-framework


【解决方案1】:

我认为您首先检索所有记录,然后计算它们。你应该直接统计你的记录。

using(DatabaseContext db = new DatabaseContext())
{
    //what I think you are doing:
    int countLong = db.UserAccount.ToList().Count();
    //what you should be doing
    int countShort = db.UserAccount.Count();
    //include where clauses inside count, wrong way:
    int countLong2 = db.UserAccount.ToList().Count(x => x.Active);
    //include where clauses inside count, good way:
    int countShort2 = db.UserAccount.Count(x => x.Active);

    //or if you don't like lambda expressions.
    int countLong3 = (from x in db.UserAccount
                      //where x.Active //optional
                      select x).ToList().Count();

    int countShort3 = (from x in db.UserAccount
                      //where x.Active //optional
                      select x).Count();

}

DatabaseContext 将是您扩展 DbContext 类的类

【讨论】:

    【解决方案2】:

    您可以尝试如下所示。该查询将返回IQueryable结果。这意味着count操作发生在数据库中。

    基于查询:

    var countVal = (from a in context.yourTable
                    select a).Count();
    

    基于方法:

    var countVal = context.yourTable.Count()
    

    【讨论】:

    • 或者干脆context.yourTable.Count()
    • 我发现这会转化为一些性能非常差的 SQL,它会遍历数据库中的每一行:SELECT [GroupBy1].[A1] AS [C1] FROM ( SELECT COUNT(1) AS [A1] FROM [dbo].[Log] AS [Extent1] ) AS [GroupBy1] - 我建议使用原始 SQL,我还没有找到其他方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多