我正在使用实体框架来获取一个包含数百万条记录的简单rowcount表,而且我不想要任何where子句。 我试图使用Count方法,但获取计数需要很长时间。是否有任何有效的方法来获取等待那么长的计数?
答案 0 :(得分:4)
我认为您首先检索所有记录然后计算它们。你应该直接计算你的记录。
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
类
答案 1 :(得分:2)
您可以尝试如下所示。此查询将返回IQueryable
结果。这意味着count
操作在数据库中发生。
基于查询:
var countVal = (from a in context.yourTable
select a).Count();
基于方法:
var countVal = context.yourTable.Count()