Get total row count in Entity Framework

c# entity-framework sql-server

Question

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();
        }
    }
1
18
8/28/2013 2:24:34 PM

Accepted Answer

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.

6
8/28/2013 2:28:36 PM

Popular Answer

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


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow