1

what is the best way to check that there are no rows in a table in entity framework?

I have this piece of code

context.users.Count() ==0

but I think that it could be expensive to count the rows in a table to check if there are rows in the table or not, so is there any other way to do this.

Mo Haidar
  • 3,748
  • 6
  • 37
  • 76
  • May be your can find answer from this Post. [How to COUNT rows within EntityFramework without loading contents?][1] [1]: http://stackoverflow.com/questions/890381/how-to-count-rows-within-entityframework-without-loading-contents – rafat Aug 13 '15 at 10:18

2 Answers2

3

You can use Take(1).Count().

To check if no row exists check the count like this.

if (context.users.Take(1).Count() == 0)
{
// do something 
}
Anuj
  • 66
  • 2
2

I think, the must readable way is using context.users.Any().Which, EF translates it to:

SELECT 
  CASE WHEN ( EXISTS (SELECT 
    1 AS [C1]
    FROM [dbo].[users] AS [Extent1]
  )) THEN cast(1 as bit) ELSE cast(0 as bit) END AS [C1]
  FROM  ( SELECT 1 AS X ) AS [SingleRowTable1]
Taher Rahgooy
  • 6,528
  • 3
  • 19
  • 30