2014-03-14 78 views
0

我已經創建了一個變量來檢查數據庫中是否存在一行。但是,當我把變量放在一個if語句中來檢查它是否爲null並且該變量爲null時,它總是轉到else而不是繼續if語句。檢查空變量C#

是否有另一種方法檢查變量是否爲空而不是== null

var following = objCtx.Followusers.Where(c => c.User1ID == currentUser.Id || c.User2ID == cus.Id); 
if (following == null) 
{ 
    using (Html.BeginForm("Followruser", "Users")) 
    { 
     @Html.AntiForgeryToken() 
     @Html.ValidationSummary(true) 

     @Html.Hidden("Id", Id) 
     <input type="submit" value="follow" class="btn btn-default" /> 
    } 
} 
else 
{ 
    using (Html.BeginForm("unfollowruser", "Users")) 
    { 
     @Html.AntiForgeryToken() 
     @Html.ValidationSummary(true) 

     @Html.Hidden("Id", Id) 
     <input type="submit" value="following" class="btn btn-default" /> 
    } 

} 

回答

3

Where運營商將永遠不會返回null。如果你只是想檢查一條記錄是否存在,這也是錯誤的方法。我會用Any代替。

bool following = objCtx.Followusers.Any(
    c => c.User1ID == currentUser.Id || c.User2ID == cus.Id); 
2

將其更改爲:

var following = objCtx.Followusers.Where(c => c.User1ID == currentUser.Id || c.User2ID == cus.Id).SingleOrDefault(); 

如果沒有行被發現,應該返回NULL。

+1

如果有多個記錄,將會拋出'InvalidOperationException' .. – lastr2d2

+0

良好的捕獲lastr2d2。 – HaukurHaf

0

返回的對象從不爲null,它的值可能是。 使用「FirstOrDefault()」,以使結果爲空,如果是沒有的:

var following = objCtx.Followusers.Where(c => c.User1ID == currentUser.Id || c.User2ID == cus.Id).FirstOrDefault(); 

或詢問的結果,如果有任何值:

if(following.Any()) 
+0

該查詢意味着結果集中可能有多個記錄。它可能不是這樣,但是'FirstOrDefault(...)'比這裏的'SingleOrDefault(...)'更好。 – Silvermind

0

如果你想保持你給什麼,您還可以統計謂詞返回的值的數量。

if (following != null && following.Count < 1) 

這應該適合你我認爲。

+0

不正確,結果是'IEnumerable'類型。 – Silvermind