开发者

Check for record in Table

I am trying to check for the existence of a record in a SQL table in a if statement, I was trying to us开发者_开发知识库e .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.


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.


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

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜