2012-02-22 50 views
4

UPDATE 1:獲取 「此方法或屬性不能被稱爲上的空值」 的錯誤

異常正在在這條線拋出:

client_group_details.Add(new ClientGroupDetails(

原來的問題:

我有下面的代碼,我已經從數據庫的30列數據剝離到只有2列從數據庫。我得到一個錯誤,每當任何列返回NULL值:

public class ClientGroupDetails 
{ 
    public String Col2; 
    public String Col3; 

    public ClientGroupDetails(String m_Col2, String m_Col3) 
    { 
     Col2 = m_Col2; 
     Col3 = m_Col3; 
    } 

    public ClientGroupDetails() { } 
} 

[WebMethod()] 
public List<ClientGroupDetails> GetClientGroupDetails(string phrase) 
{ 
    var client_group_details = new List<ClientGroupDetails>(); 

    using (connection = new SqlConnection(ConfigurationManager.AppSettings["connString"])) 
    { 
     using (command = new SqlCommand(@"select col2, col3 where col1 = @phrase", connection)) 
     { 
      command.Parameters.Add("@phrase", SqlDbType.VarChar, 255).Value = phrase; 

      connection.Open(); 
      using (reader = command.ExecuteReader()) 
      { 
       int Col2Index = reader.GetOrdinal("col2"); 
       int Col3Index = reader.GetOrdinal("col3"); 

       while (reader.Read()) 
       { 
        client_group_details.Add(new ClientGroupDetails(
         reader.GetString(Col2Index), 
         reader.GetString(Col3Index))); 
       } 
      } 
     } 
    } 

    return client_group_details; 
} 

我得到的錯誤是:

數據爲空。無法在Null值上調用此方法或屬性。

我不確定在這裏處理NULL值是什麼,因爲上面的代碼是一個精簡版。

任何人都知道如何解決這個問題?

+1

哪行代碼導致異常被拋出?什麼是異常類(例如'ArgumentNullException')? – 2012-02-22 15:42:08

+0

看來你並不是第一個得到這種例外的人,並且發佈了它。有人在使用TFS時發現了這種問題,具體的異常類型是'SqlNullValueException'(請參閱http://social.msdn.microsoft.com/Forums/zh-cn/tfsversioncontrol/thread/c7ee4549-eea6-4536- 9f9b-bcfce2b1e404)。 – 2012-02-22 15:43:37

+0

這不是數據庫意義上的「NULL」。這是一個'空'的意思是參考沒有價值。你看到的確切例外是什麼? 'ArgumentNullException'? – 2012-02-22 15:43:55

回答

5

這是因爲reader.GetString不應該在DBNull值上被調用。嘗試更改您的代碼,如下所示:

client_group_details.Add(new ClientGroupDetails(
    reader.IsDbNull(Col2Index) ? null : reader.GetString(Col2Index), 
    reader.IsDbNull(Col3Index) ? null : reader.GetString(Col3Index))); 
1

你需要調用GetString前使用IsDBNull以便於檢查列爲空,一樣的東西:

string s1, s2; 

if (reader.IsDbNull(Col1Index) == false) 
{ 
    s1 = reader.GetString(Col1Index); 
} 

if (reader.IsDbNull(Col2Index) == false) 
{ 
    s2 = reader.GetString(Col2Index); 
} 

client_group_details.Add(new ClientGroupDetails(s1, s2)); 
0

有幾個方法可以做到這一點,但我覺得你的代碼,最好的方法是添加一個簡單的函數調用到你的SQL文本 - 即IsNull函數。

下面是手冊頁的鏈接是:IsNull MSDN reference

基本上,你會改變你的SQL文本類似於此:

"select IsNull(col2, ''), IsNull(col3, '') where col1 = @phrase" 

現在,如果在數據庫中列null,它將返回一個空白字符串。

您也可以在列上設置默認值,或者您可以在代碼端檢查System.DBNull.Value

祝你好運!

相關問題