类型为"System.DBNull"的对象不能转换为类型"System.DateTime"



如何将空值传递给system.datetime?

try
{
List<T> listData = new List<T>();
string connectionstring = ConfigurationManager.ConnectionStrings["connetionString"].ConnectionString;
NpgsqlConnection MyConnection = new NpgsqlConnection(connectionstring);
MyConnection.Open();
NpgsqlCommand cmd = new NpgsqlCommand(string.Concat(query, table), MyConnection);
cmd.CommandType = CommandType.Text;
cmd.Connection = MyConnection;
NpgsqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
T objCodeName = new T();
PropertyInfo[] properties = objCodeName.GetType().GetProperties();
foreach (PropertyInfo prop in properties)
{
prop.SetValue(objCodeName, dr[prop.Name]);
}
listData.Add(objCodeName);
}
dr.Close();
Message message = new Message();
message.data = listData;
return message;
}
catch (Exception e)
{
Message message = new Message();
message.message = e.Message;
return message;
}

您可以在访问数据读取器值时检查DBNull,如下所示:

while (dr.Read())
{
T objCodeName = new T();
PropertyInfo[] properties = objCodeName.GetType().GetProperties();
foreach (PropertyInfo prop in properties)
{
if (!(dr["prop.Name"] is DBNull))
{
prop.SetValue(objCodeName, dr[prop.Name]);  
}
}
listData.Add(objCodeName);
}

相关内容

  • 没有找到相关文章

最新更新