Reputation: 493
I am using entity framework to get a simple rowcount of table with millions of records and I don't want any where clause. I tried to use the Count method but it is taking very long to fetch the count. Is there any efficient way to fetch the count with waiting that long?
Upvotes: 0
Views: 6985
Reputation: 10321
I think you are first retrieving all records and then count them. You should directly count your records.
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
would be your class that extends DbContext
class
Upvotes: 5
Reputation: 65880
You can try as shown below.This query will return a IQueryable
result.That means count
operation happens in the database.
Query Based :
var countVal = (from a in context.yourTable
select a).Count();
Method Based :
var countVal = context.yourTable.Count()
Upvotes: 2