2012-02-25 22 views
2

爲什麼我的代碼表明這個代碼塊語法錯誤LINQ到SQL看到,如果還沒有結果

public string getPassword() 
{ 
    DataClasses1DataContext myDbContext = new DataClasses1DataContext(dbPath); 

    var password = (from user in myDbContext.Accounts 
        where user.accnt_User == txtUser.Text 
        select user.accnt_Pass).First(); 

    if (password == 0) 
    { } 

    return password; 
} 

我想知道,如果查詢的結果爲0,如果是0我會關閉操作或類似的東西。但它不斷顯示一個錯誤,我怎麼知道結果是0?此外,如果您對我的方法的建議隨時把它放在

+1

什麼是錯誤? – 2012-02-25 11:07:12

+0

「accnt_Pass」字段的類型是什麼?我認爲它不是'int',並且將它與'0'比較。 – 2012-02-25 11:08:16

+0

你想知道密碼是否等於0?或者這個用戶沒有密碼? – Akrem 2012-02-25 11:11:26

回答

4

調用.First()將導致異常,如果沒有數據返回...

調用.FirstOrDefault()將返回null如果沒有數據

public string getPassword() 
{ 
    DataClasses1DataContext myDbContext = new DataClasses1DataContext(dbPath); 

    var password = (from user in myDbContext.Accounts 
        where user.accnt_User == txtUser.Text 
        select user.accnt_Pass).FirstOrDefault(); 

    if (password == null) 
    { 
     // no data found - do whatever is needed in that case... 
    } 

    return password; 
}