2010-08-13 39 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