0

我的代码是:当我执行断点时,我正在从数据库中检索数据,它显示列表中的数据,但它也给了我一个错误

    public static List<StudentScore> GetAllScore()
   {
       SqlConnection conn = MyDB.GetConnection();
       string selectStm = "SELECT en.CourseID,en.Score,s.StudentID FROM EnrollmentTable en,Student s WHERE en.StudentID = s.StudentID";
       SqlCommand command = new SqlCommand(selectStm, conn);
       List<StudentScore> aStudentScore = new List<StudentScore>();
       try
       {
           conn.Open();
           SqlDataReader reader = command.ExecuteReader();          
           Console.WriteLine(reader.HasRows.ToString());
           while (reader.Read())
           {
               StudentTable st = new StudentTable();
               CourseTable cr = new CourseTable();
               Enrollment enr = new Enrollment();
               StudentScore score = new StudentScore();
               enr.CourseData = cr;
               enr.StudentData = st;                                    
                   //score.EnrollmentData.StudentData.StudentID = reader["StudentID"].ToString();
                   //score.EnrollmentData.CourseData.CourseID = reader["CourseID"].ToString();                  
                   st.StudentID = reader["StudentID"].ToString();
               cr.CourseID = reader["CourseID"].ToString();
               score.Score = Convert.ToInt32(reader["Score"]);
               score.EnrollmentData = enr; 
               aStudentScore.Add(score);
           }
           reader.Close();
           return aStudentScore;
       }
       catch (SqlException ex)
       {
           throw ex;
       }
       finally
       {
           conn.Close();
       }

   }


}

}

它从数据库中获取数据,但显示 mw 这个错误.....对象不能从 DBNull 转换为其他类型,所以这意味着什么,请告诉我如何解决它?

4

3 回答 3

5

这意味着您NULL在数据库中有一个值。您必须在代码中检查它,或者将您的列模式更改为NOT NULL.

st.StudentID = reader["StudentID"] == DBNull.Value ? null : reader["StudentID"].ToString();
cr.CourseID = reader["CourseID"] == DBNull.Value ? null : reader["CourseID"].ToString();
score.Score = reader["Score"] == DBNull.Value ? 0 : Convert.ToInt32(reader["Score"]);

您现在必须处理nullC# 对象中的值。

于 2012-08-10T16:31:31.473 回答
3

您需要检查阅读器是否为 DBNULL 类型

在尝试转换之前调用阅读器上的 IsDBNull() 以检查该列:

using (reader = server.ExecuteReader(CommandType.Text, TopIDQuery, paramet))
{
   while (reader.Read())
   {
       var column = reader.GetOrdinal("TopID");

       if (!reader.IsDBNull(column))
          topID = Convert.ToInt32(reader[column]);
       }
   }
}

或者,与 DBNull.Value 进行比较:

var value = reader["TopID"];

if (value != DBNull.Value)
{
    topID = Convert.ToInt32(value);
}
于 2012-08-10T16:32:24.827 回答
2

DBNull 用于表示数据库中的空值。

您应该在转换 ir 之前检查该值是否不是 DBNull。

object score = reader["Score"];

score.Score = score == DBNull.Value ? 0 : Convert.ToInt32(score);
于 2012-08-10T16:33:47.063 回答