大家好,我正在使用存储过程从 sql server 读取数据,当数据库中有空数据时,一切看起来都是异常的,我无法将 DBNull 转换为其他类型。我正在使用 .net MVC3 以下是我的代码:
public static List<XYZFactorsModel> SelectGridItems(string sidx, string sord, int page, int rows, String rid, String process, String detail_table, String jobGroup, String date)
{
const string spName = "dbo.p___GetXYZMonitorJobDetails";
List<XYZFactorsModel> XYZFactorDetailGridCollection;
string connectionString = ConfigurationManager.ConnectionStrings["AdvItemsContext"].ConnectionString;
if (string.IsNullOrEmpty(connectionString))
return null;
using (SqlConnection sqlConnection = new SqlConnection(connectionString))
{
SqlCommand sqlCommand = new SqlCommand(spName, sqlConnection);
sqlCommand.CommandType = CommandType.StoredProcedure;
//sqlCommand.Parameters.Add("@jobDate", SqlDbType.VarChar);
sqlCommand.Parameters.Add("@jobGroup", SqlDbType.VarChar);
sqlCommand.Parameters.Add("@jobName", SqlDbType.VarChar);
sqlCommand.Parameters.Add("@detailTable", SqlDbType.VarChar);
sqlCommand.Parameters.Add("@filterBatchControl", SqlDbType.VarChar);
sqlCommand.Parameters.Add("@filterDate", SqlDbType.VarChar);
sqlCommand.Parameters.Add("@filterTime", SqlDbType.VarChar);
//sqlCommand.Parameters["@jobDate"].Value = date2;
sqlCommand.Parameters["@jobGroup"].Value = jobGroup;
sqlCommand.Parameters["@jobName"].Value = process;
sqlCommand.Parameters["@detailTable"].Value = detail_table;
sqlCommand.Parameters["@filterBatchControl"].Value = rid;
sqlCommand.Parameters["@filterDate"].Value = date;
sqlCommand.Parameters["@filterTime"].Value =date;
sqlConnection.Open();
XYZFactorDetailGridCollection = FillGridEntity(sqlCommand);
}
return XYZFactorDetailGridCollection;
}
private static List<XYZFactorsModel> FillGridEntity(SqlCommand sqlCommand)
{
List<MBSFactorsModel> thegrid = new List<MBSFactorsModel>();
using (SqlDataReader sqlDataReader = sqlCommand.ExecuteReader())
{
while (sqlDataReader.Read())
{
try
{
//if(sqlDataReader["last_factor"] != System.DBNull.Value)
//{
//
// thegrid.Add(new XYZFactorsModel
// {
// last_factor = Convert.ToDateTime(sqlDataReader["last_factor"])
// });
//}
//else
//{
// System.Diagnostics.Debug.WriteLine("null value was found in last factor field");
// }
thegrid.Add(new XYZFactorsModel
{
abc = sqlDataReader["abc"].ToString(),
abc2 = sqlDataReader["abc2"].ToString(),
abc3 = sqlDataReader["abc3"].ToString(),
abc4 = sqlDataReader["abc4"].ToString(),
abc5 = Convert.ToDecimal(sqlDataReader["abc5"]),
last_factor = Convert.ToDateTime(sqlDataReader["last_factor"]),
});
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
}
}
return thegrid;
}
}