获取“无法在Null值上调用此方法或属性”错误

更新1:

这条线上引发了exception:

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 GetClientGroupDetails(string phrase) { var client_group_details = new List(); 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值,因为上面的代码是一个精简版本。

有谁知道如何解决这个问题?

这是因为不应该在DBNull值上调用reader.GetString 。 尝试更改代码,如下所示:

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

在调用GetString之前,您需要使用IsDbNull来检查列是否为null,例如:

 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)); 

有几种方法可以做到这一点,但我认为代码的最佳方法是为SQL文本添加一个简单的函数调用 – 即IsNull函数。

以下是指向此手册页的链接: IsNull MSDN参考

基本上,您将更改SQL文本看起来类似于:

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

现在,如果DB中的列为null,它将返回一个空字符串。

您还可以在列上设置默认值,也可以在代码端检查System.DBNull.Value

祝好运!