2012-02-22 60 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

祝你好运!

相关问题