Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Object reference not set to an instance of an object

Posted on 2014-08-14
4
Medium Priority
?
388 Views
Last Modified: 2014-08-15
I keep getting this when I try to create a new employee in my application.  

Here's my code: this is on an EmployeeController.cs file,   the problem is on the department.Employees line.

  [HttpPost]
        public ActionResult Create(CreateEmployeeViewModel viewModel)
        {
            if (ModelState.IsValid)
            {
                var department = _db.Departments.Single(d => d.ID == viewModel.DepartmentID);
                var employee = new Employee();
                employee.Name = viewModel.Name;
                employee.HireDate = viewModel.HireDate;
                department.Employees.Add(employee);

                _db.Save();

                return RedirectToAction("detail", "department", new { id = viewModel.DepartmentID });
            }
            return View(viewModel);
        }

I haven't been able to find the issue.  Any help is greatly appreciated.  I'm working on learning this.
0
Comment
Question by:Sherry
  • 2
  • 2
4 Comments
 
LVL 75

Accepted Solution

by:
käµfm³d   👽 earned 2000 total points
ID: 40262235
You context isn't instantiating the Employees member. You either need to fix your Department class to properly instantiate Employees (to an empty List), or you need to code defensively in what you've shown.

e.g.

var department = _db.Departments.Single(d => d.ID == viewModel.DepartmentID);
if (department.Employees == null) department.Employees = new List<Employee>();

Open in new window

0
 

Author Comment

by:Sherry
ID: 40263971
I wouldn't accept the second line of code you gave.  Does it make the difference that this is a >Net4 MVC Web app?  Here's the code for the whole EmployeeController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using eManager.Web.Models;
using eManager.Domain;

namespace eManager.Web.Controllers
{
    public class EmployeeController : Controller
    {
        private readonly IDepartmentDataSource _db;

        public EmployeeController(IDepartmentDataSource db)
        {
            _db = db;
        }
       
        [HttpGet]
        public ActionResult Create(int departmentId)
        {
            var model = new CreateEmployeeViewModel();
            model.DepartmentID = departmentId;
           
            return View(model);
        }

        [HttpPost]
        public ActionResult Create(CreateEmployeeViewModel viewModel)
        {
            if (ModelState.IsValid)
            {
                var department = _db.Departments.Single(d => d.ID == viewModel.DepartmentID);
                var employee = new Employee();
                employee.Name = viewModel.Name;
                employee.HireDate = viewModel.HireDate;
                department.Employees.Add(employee);

                _db.Save();

                return RedirectToAction("detail", "department", new { id = viewModel.DepartmentID });
            }
            return View(viewModel);
        }

    }
}

There is also a Create.cshtml and a CreatEmployViewModel.cs  I'm going over some other code to make sure I didn't make a mistake in it.  I'm following a lesson from pluralsight.

Thanks
Sherry
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 40264018
I wouldn't accept the second line of code you gave.
I'm not sure what you mean.

Does it make the difference that this is a >Net4 MVC Web app?
It shouldn't. You may need to make a change to the data context.

I'm following a lesson from pluralsight.
Which one?
0
 

Author Comment

by:Sherry
ID: 40264042
Pluralsight ASP.Net MVC 4 Fundamentals

when I put in the code you gave, sorry, I just had to leave the line of code in that I had originally also.
var employee = new Employee();

That seems to have solved one problem.  Now my savechanges need work.  Doesn't like the datatime data type.
resulted in out of range.  So, onward and upward in my learning.

I'll go ahead and accept the solution.  Thank you.  I must have missed something in another file, because the original code worked before.  The only difference is that I'm doing an intranet vs internet app.
0

Featured Post

Get your Conversational Ransomware Defense e‑book

This e-book gives you an insight into the ransomware threat and reviews the fundamentals of top-notch ransomware preparedness and recovery. To help you protect yourself and your organization. The initial infection may be inevitable, so the best protection is to be fully prepared.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
Q&A with Course Creator, Mark Lassoff, on the importance of HTML5 in the career of a modern-day developer.
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.
Suggested Courses
Course of the Month21 days, 6 hours left to enroll

810 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question