If you're querying against the whole database anyway, as you mentioned in your comment, you can go with querying the DbSet's Count, even though that will fetch all rows from the database.
static void Main(string[] args)
{
using (var context = new EntityContext())
{
context.Entities.Add(new MyEntity());
context.Entities.Add(new MyEntity());
var myEntityCount = context.Entities.Count();
Console.WriteLine("The context now tracks {0} entities", context.Entities.Local.Count);
context.SaveChanges();
}
using (var context = new EntityContext())
{
Console.WriteLine("The db had {0} entities when I queried it", context.Entities.Count());
context.SaveChanges();
}
}
class MyEntity
{
public int MyEntityId { get; private set; }
}
class EntityContext:DbContext
{
public DbSet<MyEntity> Entities { get; set; }
}
With large amount of data in your db, you wouldn't want to do that, and you will have to resort to writing sql to return just the count of the table, without fetching everything.