0

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?

3
  • 3
    Do you have sample code? If you're using the IEnumerable version of Count(), your application would be retrieving all rows and then counting them. If you're using the IQueryable version of Count(), the database server would be doing the count and should be fast. Commented Sep 28, 2016 at 13:26
  • 1
    can you show your code so far ? Commented Sep 28, 2016 at 13:27
  • 1
    Just execute raw SQL query against the database. That's the probably fastest way to achieve this. msdn.microsoft.com/en-us/data/jj592907.aspx Commented Sep 28, 2016 at 13:34

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

Comments

2

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()

2 Comments

or simply context.yourTable.Count()
I found that this translates to some very poorly performing SQL, that iterates through every row in the DB: SELECT [GroupBy1].[A1] AS [C1] FROM ( SELECT COUNT(1) AS [A1] FROM [dbo].[Log] AS [Extent1] ) AS [GroupBy1] - I recommend using raw SQL, I haven't found another way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.