0

I am trying to implement my project with ASP.NET MVC without entity framework. I am getting my values to index fine, however my create and edit functions do not work. I clicked on create or edit and it ends up in my catch block with what appears to be a null reference exception.

I have set up my stored procedures as follows:

 CREATE PROCEDURE [Project].[AddStudent]  
(  
   @FirstName NVARCHAR(32),  
   @LastName  NVARCHAR(32),  
   @Email     NVARCHAR(32)  
)  
AS
INSERT INTO Project.Student
VALUES
(   @FirstName,
    @LastName,
    @Email
)

    CREATE PROCEDURE [Project].[UpdateStudent]  
(  
   @StudentId INT,  
   @FirstName NVARCHAR(32),  
   @LastName NVARCHAR(32),  
   @Email NVARCHAR(32)  
)  
AS   
   UPDATE Student  
   SET FirstName = @FirstName,  
   LastName = @LastName,  
   Email = @Email  
   WHERE StudentId = @StudentId

Which I believe it should work on their own. The StudentId value in the first procedure should get filled in since it is as Identity.

I then have created a db handle class:

 public class StudentDBHandle
{
    private SqlConnection con;
    private void Connection()
    {
        string constring = ConfigurationManager.ConnectionStrings["studentconn"].ToString();
        con = new SqlConnection(constring);
    }

    // **************** ADD NEW STUDENT *********************
    public bool AddStudent(Student smodel)
    {
        Connection();
        SqlCommand cmd = new SqlCommand("AddStudent", con)
        {
            CommandType = CommandType.StoredProcedure
        };

        cmd.Parameters.AddWithValue("@FirstName", smodel.FirstName);
        cmd.Parameters.AddWithValue("@LastName", smodel.LastName);
        cmd.Parameters.AddWithValue("@Email", smodel.Email);

        con.Open();
        int i = cmd.ExecuteNonQuery();
        con.Close();

        if (i >= 1)
            return true;
        else
            return false;
    }

    // ********** VIEW STUDENT DETAILS ********************
    public List<Student> GetStudent()
    {
        Connection();
        List<Student> studentlist = new List<Student>();

        SqlCommand cmd = new SqlCommand("Project.GetStudentDetails", con)
        {
            CommandType = CommandType.StoredProcedure
        };
        SqlDataAdapter sd = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();

        con.Open();
        sd.Fill(dt);
        con.Close();

        foreach (DataRow dr in dt.Rows)
        {
            studentlist.Add(
                new Student
                {
                    StudentId = Convert.ToInt32(dr["StudentId"]),
                    FirstName = Convert.ToString(dr["FirstName"]),
                    LastName = Convert.ToString(dr["LastName"]),
                    Email = Convert.ToString(dr["Email"])
                });
        }
        return studentlist;
    }

    // ***************** UPDATE STUDENT DETAILS *********************
    public bool UpdateDetails(Student smodel)
    {
        Connection();
        SqlCommand cmd = new SqlCommand("UpdateStudent", con)
        {
            CommandType = CommandType.StoredProcedure
        };

        cmd.Parameters.AddWithValue("@StudentId", smodel.StudentId);
        cmd.Parameters.AddWithValue("@FirstName", smodel.FirstName);
        cmd.Parameters.AddWithValue("@LastName", smodel.LastName);
        cmd.Parameters.AddWithValue("@Email", smodel.Email);

        con.Open();
        int i = cmd.ExecuteNonQuery();
        con.Close();

        if (i >= 1)
            return true;
        else
            return false;
    }

Which seems to be where the problem occurs, on int i = cmd.ExecuteNonQuery();

and then I have my controller as follows:

 // GET: Student/Create
    public ActionResult Create()
    {
        return View();
    }

    // POST: Student/Create
    [HttpPost]
    public ActionResult Create(Student smodel)
    {
        try
        {
            if (ModelState.IsValid)
            {
                StudentDBHandle sdb = new StudentDBHandle();
                if (sdb.AddStudent(smodel))
                {
                    ViewBag.Message = "Student Added Successfully";
                    ModelState.Clear();
                }
            }
            return View();
        }
        catch
        {
            return View();
        }
    }

    // GET: Student/Edit/5
    public ActionResult Edit(int id)
    {
        StudentDBHandle sdb = new StudentDBHandle();
        return View(sdb.GetStudent().Find(smodel => smodel.StudentId == id));
    }

    // POST: Student/Edit/5
    [HttpPost]
    public ActionResult Edit(int id, Student smodel)
    {
        try
        {
            StudentDBHandle sdb = new StudentDBHandle();
            sdb.UpdateDetails(smodel);
            return RedirectToAction("Index");
        }
        catch
        {
            return View();
        }
    }

I am new to this, especially without entity framework. So I am unsure where I am going wrong. Any help figuring out or providing me with best practice guidance would be much appreciated.

Vikas Sonichya
  • 125
  • 1
  • 6
  • What kind of error you've got when doing `ExecuteNonQuery()`? Try to use debugger and find out if you get any exception after defining command parameters. Also you should use `public ActionResult Edit(Student smodel)` instead. – Tetsuya Yamamoto Nov 27 '18 at 05:56
  • why not use Dapper framework instead of writing raw sql connection objects? I have switched to Dapper and never look at face of entity framework again in my career so far! – vibs2006 Nov 27 '18 at 05:56
  • I believe I have to use raw sql connections since part of the project requirements lead me to believe that I am not suppose to use framework to help my sql – RobWantsToLearn Nov 27 '18 at 06:01
  • It seems that when my cmd.Parameters.AddWithValue statements are being ran, the parameters all are showing null reference exceptions in the debugger – RobWantsToLearn Nov 27 '18 at 06:03
  • Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Tetsuya Yamamoto Nov 27 '18 at 06:06
  • Ah actually the problem is that I named my schema "Project" so I instead of "AddStudent" I needed to put "Project.AddStudent". Error was it couldnt find my stored procedure. Thank you! – RobWantsToLearn Nov 27 '18 at 06:09
  • You can check inner exception to find out what causes null reference exception – Nayas Subramanian Nov 27 '18 at 06:43

1 Answers1

0

Remove ID parameter from overload Edit method like

[HttpPost]
public ActionResult Edit(Student smodel)
{
    try
    {
        StudentDBHandle sdb = new StudentDBHandle();
        sdb.UpdateDetails(smodel);
        return RedirectToAction("Index");
    }
    catch
    {
        return View();
    }
}