use*_*667 0 c# c#-to-vb.net c#-3.0 c#-4.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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
}
它从数据库中获取数据,但向mw显示此错误.....无法将对象从DBNull强制转换为其他类型,所以这意味着什么,请告诉我如何解决?
这意味着您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"]);
Run Code Online (Sandbox Code Playgroud)
您现在必须处理nullC#对象中的值。