Why am I getting a null pointer error in my view model ASP.NET MVC

Viewed 50

I am currently trying to read data from a database and send that data into a list so that I can display the data items in a list however, I am getting a null pointer error in my view near my foreach loop.

Controller:

public ActionResult Index()
    {

        try
        {
            connection.Open();
            SqlCommand myCommand = new SqlCommand("SELECT Firstname, ExerciseName, PR_Weight FROM Users, Exercises, PR WHERE Exercises.ExerciseID = PR.ExerciseID AND PR.Username = Users.Username AND Firstname = 'Evan' ", connection);
            SqlDataReader myReader = myCommand.ExecuteReader();
            Globals.PRList.Clear();
            while (myReader.Read())
            {
                PRViewModel pr = new PRViewModel();

                pr.PR_ID = (int)myReader["PR_ID"];
                pr.Username = myReader["Username"].ToString();
                pr.ExerciseID = (int)myReader["ExerciseID"];
                pr.PR_Weight = (int)myReader["PR_Weight"];
                pr.PR_Date = myReader["PR_Date"].ToString();
                pr.Exercises.exerciseID = (int)myReader["ExerciseID"];
                pr.Exercises.exercsieName = myReader["ExerciseName"].ToString();
                Globals.PRList.Add(pr);
            }
        }
        catch (Exception err)
        {

            ViewBag.Status = 0;
        }
        finally
        {
            connection.Close();
        }

        return View(Globals.PRList);
    }

Globals Class:

public static class Globals
{
    public static string myConnection = @"Data Source=TYRONSSPEEDYBOY\SQLEXPRESS02;Initial Catalog=PR_Tracker_DB1;Integrated Security=True";
    public static List<PRViewModel> PRList = new List<PRViewModel>();
}

Index View:

 @foreach (PRViewModel pr in Model)
{
<tr>
    <td>@pr.PR_ID</td>
    <td>@pr.Username</td>
    <td>@pr.ExerciseID</td>
    <td>@pr.PR_Weight</td>
    <td>@pr.PR_Date</td>

PRViewModel:

public PRViewModel()
    {
        Exercises = new ExerciseViewModel();
    }

    public int PR_ID { get; set; }
    public string Username { get; set; }
    public int ExerciseID { get; set; }
    public int PR_Weight { get; set; }
    public string PR_Date { get; set; }
    public ExerciseViewModel Exercises { get; set; }
1 Answers

You select these fields from the database

SELECT Firstname, ExerciseName, PR_Weight

But you then go on to read out several values which don't exist in the reader (because they're not returned by your query)

  • PR_ID
  • Username
  • List item
  • ExerciseID
  • PR_Weight
  • PR_Date
  • ExerciseID
  • ExerciseName (only this one exists in your query)

Try correcting your query. Your code also assumes none of these fields are null in the database, if they are casting is likely to fail.

Related