Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get total row count in Entity Framework

I'm using Entity Framework to get the total row count for a table. I simply want the row count, no where clause or anything like that. The following query works, but is slow. It took about 7 seconds to return the count of 4475.

My guess here is that it's iterating through the entire table, just like how IEnumerable.Count() extension method works.

Is there a way I can get the total row count "quickly"? is there a better way?

    public int GetLogCount()
    {
        using (var context = new my_db_entities(connection_string))
        {
            return context.Logs.Count();
        }
    }
like image 327
Stealth Rabbi Avatar asked Aug 28 '13 14:08

Stealth Rabbi


2 Answers

You can even fire Raw SQL query using entity framework as below:

var sql = "SELECT COUNT(*) FROM dbo.Logs";
var total = context.Database.SqlQuery<int>(sql).Single();
like image 131
Bhushan Firake Avatar answered Sep 21 '22 19:09

Bhushan Firake


That is the way to get your row count using Entity Framework. You will probably see faster performance on the second+ queries as there is an initialization cost the first time that you run it. (And it should be generating a Select Count() query here, not iterating through each row).

If you are interested in a faster way to get the raw row count in a table, then you might want to try using a mini ORM like Dapper or OrmLite.

You should also make sure that your table is properly defined (at the very least, that it has a Primary Key), as failure to do this can also affect the time to count rows in the table.

like image 40
Yaakov Ellis Avatar answered Sep 23 '22 19:09

Yaakov Ellis