更新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 值,因为上面的代码是一个精简版本。
有人知道如何解决这个问题吗?
这是因为reader.GetString
不应该被召唤DBNull
价值观。尝试按如下方式更改您的代码:
client_group_details.Add(new ClientGroupDetails(
reader.IsDbNull(Col2Index) ? null : reader.GetString(Col2Index),
reader.IsDbNull(Col3Index) ? null : reader.GetString(Col3Index)));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)