6

Im looking for otimization.

When I call Count method in Entity Framework, does it process all the columns or only one or what?

If you also have any official site talking about this, I would appreciate.

Thank you.

alansiqueira27
  • 8,129
  • 15
  • 67
  • 111

1 Answers1

7

I did some tests a while ago and found out that EF does a count on the server, it sends a query with a SELECT COUNT so it does not load all records for sure.

about the columns, if you are referring to the difference between COUNT(*) or COUNT(Id) or COUNT(1) I have read somewhere a while ago that for SQL Server there is no difference, the COUNT(*) is optimized as COUNT(1) anyway.

you could read many articles online or question here on SO... not excatly 100% what you asked but similar topics on performances of EF and ORM...

How to COUNT rows within EntityFramework without loading contents?

http://ayende.com/blog/4387/what-happens-behind-the-scenes-nhibernate-linq-to-sql-entity-framework-scenario-analysis

How to optimize Entity Framework Queries

Community
  • 1
  • 1
Davide Piras
  • 43,984
  • 10
  • 98
  • 147
  • 2
    You beat me to it. I was also going to add the link to a post about the performance of Count in general http://geekswithblogs.net/BlackRabbitCoder/archive/2011/06/02/c.net-little-wonders-empty-defaultifempty-and-count.aspx – John Kalberer Sep 28 '11 at 22:14
  • SQL Profiler enabled, then make a sample program in .NET and EF and capture all calls to the database. You are using MS SQL Server right? – Davide Piras Sep 28 '11 at 22:25
  • actually Im using mysql, but I dont think there will be a difference. Well, you said the query was "SELECT COUNT", but was that "SELECT COUNT (*) or SELECT COUNT (column_name)". If im not wrong, the count with column_name is faster and dont bring all the data. – alansiqueira27 Sep 28 '11 at 22:32
  • it was surely not a *, was COUNT(1) and you can test this against SQL Server. Is there a connector EF -> MySQL already?! – Davide Piras Sep 28 '11 at 22:36
  • good! yes there is already an official connector: http://www.mysql.com/downloads/connector/net/ hey, can you check if the query using a WHERE name.Contains("Jack") still COUNT(1)? Because this way, the result may be different of a GetAll count. Thank you. – alansiqueira27 Sep 28 '11 at 22:45
  • I will try this SQL Profiller to do more tests ^^ – alansiqueira27 Sep 28 '11 at 22:51