For testing I introduced in my DB a row with a null field. now I am receiving this error when I want get the record for updating:
InvalidCastException: Unable to cast object of type 'System.DBNull' to type 'System.String'.
the code I am using works fine where all fields are not null, it is: for the model :
using System.Data;
namespace ContosoSite.Models.Services
{
public class StudentEnrollmentList
{
public int ID { get; set; }
public string? Grade { get; set; }
public string Title { get; set; }
public int Credits { get; set; }
public static StudentEnrollmentList FromDataRow (DataRow row)
{
StudentEnrollmentList studentEnrollmentList = new()
{
ID=(int)row["EnrollmentID"],
Grade=(string)row["Grade"]+"",
Title=(string)row["Title"],
Credits=(int)row["Credits"]
};
return studentEnrollmentList;
}
}
}
and for the controller :
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
//in questo punto
var student = await _context.GetStudent((int) id);
if (student == null)
{
return NotFound();
}
return View(student);
}
in the service I am using this:
var studentCoursesDT=dataSet.Tables[1];
foreach(DataRow row in studentCoursesDT.Rows)
{
StudentEnrollmentList enrollments = StudentEnrollmentList.FromDataRow(row);
curStudent.Enrollments.Add(enrollments);
}
so, if I can't get the entire record with all of the list I can't update the error