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

   }


}

}

データベースからデータを取得しますが、このエラーが表示されます.....オブジェクトは 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"]);

nullここで、C# オブジェクトの値を処理する必要があります。

于 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は、データベース内のnull値を表すために使用されます。

irをキャストする前に、値がDBNullでないかどうかを確認する必要があります。

object score = reader["Score"];

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