0

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

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

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179

2 Answers2

0

few minute ago I found this:

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=Value==DBNull?null:(string)row["Grade"],
           Grade=row.Field<string>("Grade"),
            Title=(string)row["Title"],
            Credits=(int)row["Credits"]
        };
        return studentEnrollmentList;
    }
}

}

and it was ok !

0

If you want Grade as empty string if it is null in db, use:

Grade = row["Grade"] == DBNull.Value ? string.Empty : (string)row["Grade"]

Otherwise you want Grade as null if it is null in db, use:

Grade = row["Grade"] == DBNull.Value ? null : (string)row["Grade"]
Furkan Öztürk
  • 1,178
  • 11
  • 24