2010-08-13 38 views
1

我想检查是否存在记录在一个SQL表中的一个if语句,我试图使用.Count(),但现在明白它不会工作,因为它会返回表中所有记录的总数。检查记录在表

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

} 

我有点新手的时候谈到这个,但我已经做了一些搜索网的,似乎无法找到任何熄灭。

+1

请不要在标题中加入“with asp.net mvc 2 c#SQL LINQ”之类的内容。这些都属于标签,因为它只是为了对问题进行分类。 – 2010-08-13 02:45:39

+0

对不起约翰,有没有办法让我改变标题? – bEUY 2010-08-13 04:50:16

回答

2

正确的解决方法是:

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

这确保了数据库将停止寻找,一旦发现之一。如果您使用.Where(),然后是.Count(),则它可能会遍历整个表格并检索比必要的更长的列表。

+0

太棒了!为我工作Timwi,并感谢您通过整个表的.Where()和.Count()的信息,我不知道这一点。 – bEUY 2010-08-13 03:43:32

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

} 
+0

由于代码错误(它只检查数据库中是否有用户)并且因为效率非常低而被降级。 – Timwi 2010-08-13 03:06:56