tags:

views:

26

answers:

2

I am trying to check for the existence of a record in a SQL table in a if statement, I was trying to use .Count() but now understand that it won't work as it will return the total amount of all records in the table.

// If the current user does not exist in the Database, then add the user
if (staffdb.Staffs.Single(s => s.Staffname == user).Count() == 0)
{

}

I'm a bit of a novice when it comes to this but I've done a bit of searching the net and can't seem to find anything to go off.

A: 
// If the current user does not exist in the Database, then add the user
if (staffdb.Staffs.SingleOrDefault(s => s.Staffname == user) == null)
{

}
Leniel Macaferi
Downvoted because the code is wrong (it only checks whether there is a user in the db at all) and because it is very inefficient.
Timwi
+2  A: 

The correct solution is:

if (!staffdb.Staffs.Any(s => s.Staffname == user))
{
    // ...
}

This ensures that the database will stop looking once it finds one. If you use .Where() followed by .Count(), it will potentially go through the entire table and retrieve a longer list than necessary.

Timwi
Fantastic! Works for me Timwi and thank you for the information regarding .Where() and .Count() going through the entire table, I wasn't aware of that.
bEUY