Get total row count in Entity Framework

c# entity-framework sql-server

Question

To determine the total number of rows in a table, I'm using Entity Framework. Without a where clause or anything of the sort, I just need the number of rows. The following query is functional but sluggish. The count of 4475 was returned after around 7 seconds.

My best assumption is that, like the IEnumerable.Count() extension approach, it is iterating through the full table.

Is there a method for me to "fast" obtain the entire number of rows? Exists a better approach?

    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

Using Entity Framework, you may calculate your row count in this manner. Given that there is a penalty for initialization the first time you run it, you will probably notice faster performance for queries that take more than two seconds. ( And it ought to be producing aSelect Count() not iterating over each row in this query).

Try utilizing a mini ORM like Dapper or OrmLite if you're looking for a quicker approach to determine the raw row count in a table.

As failure to do so can potentially effect the time to count rows in the database, you should also ensure that your table is properly defined (at the very least, that it has a Primary Key).

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

Popular Answer

Using entity framework, you can also do a raw SQL query like shown 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