DropDownFor issue in MVC 3

I'm new to the Entity Framework and ran into a little problem with the 'DropDownListFor 'method in the UI. I would like to stay consistent with in building loosely-coupled components as much as possible. Here is the scenerio, each employee can only be associated with one department, and a department can be associated with many employees. When I add an employee to the database, I would like to select the department from a drop-down list, which is populated from the departments table. This is straight-forward, however, when I create a new employee, it gives me this error (pictured below). When using the ViewResult edit method, the drop-down list works fine.

I was thinking, could this be a result that a department id doesn't yet exist for the employee? Then on the other hand, these values are from the departments table, so it shouldn't matter if a department id exists yet or not. Any help would be appreciated.
[Table("Employees")]
    // The employee class
    public class EEmployee
    {
        [Key]
        public int EmployeeID { get; set; }

        public string FirstName { get; set; }
        public string LastName { get; set; }
        public bool IsDateAdded { get; set; }
        public DateTime DateAdded { get; set; }
        public DateTime DateModified { get; set; }
        public string AddedBy { get; set; }
        public string ModifiedBy { get; set; }
        public string Notes { get; set; }

        #region Foreign keys and navagation properties
        // An employee can only have one department.
        public int DepartmentID { get; set; }
        public EDepartment Department { get; set; }

        // An employee can have many EmployeeLdrs.
        public ICollection<ELdrEmployeeProductionRecord> Ldrs_Employees_ProductionRecords { get; set; }

        // An employee can have many error reports.
        public ICollection<EErrorReport> ErrorReports { get; set; }

        // An employee can have many transfer ins.
        public ICollection<ETransferIn> TransferIns { get; set; }

        // An employee can have many transfer outs.
        public ICollection<ETransferOut> TransferOuts { get; set; }
        #endregion
    }

Open in new window

// The IEmployeeRepository interface
public interface IEmployeeRepository
    {
        IQueryable<EEmployee> Employees { get; }
        void Save(EEmployee employee);
        void Delete(EEmployee employee);
        IEnumerable<EDepartment> Departments { get; }
    }

Open in new window

// The employee concrete type for EF
public class EFEmployeeRepository : IEmployeeRepository
    {
        private EFBrodartProjectContext context = new EFBrodartProjectContext();

        public IQueryable<EEmployee> Employees
        {
            get { return context.Employees; }
        }

        public IEnumerable<EDepartment> Departments
        {
            get { return context.Departments; }
        }

        public void Save(EEmployee employee)
        {
            if (employee.EmployeeID == 0)
            {
                context.Employees.Add(employee);
                context.SaveChanges();
            }

            context.SaveChanges();
        }

        public void Delete(EEmployee employee)
        {
            context.Employees.Remove(employee);
            context.SaveChanges();
        }
    }

Open in new window

// Custom employee view model
public class VMEmployee
    {
        public EEmployee Employee { get; set; }
        public IEnumerable<EEmployee> Employees { get; set; }
        public EDepartment Department { get; set; }
        public IEnumerable<EDepartment> Departments { get; set; }
        public VMPaging Paging { get; set; }
    }

Open in new window

private readonly IEmployeeRepository employeeRepository;

        public EmployeeController(IEmployeeRepository employeeRepository)
        {
            if (employeeRepository == null)
            {
                throw new ArgumentNullException("An error has occurred. Please try again.");

                // Dump error messages into the database.
            }
            else
            {
                this.employeeRepository = employeeRepository;
            }
        }

public ViewResult Edit(int id)
        {
            VMEmployee viewModel = new VMEmployee
            {
                Employee = employeeRepository.Employees.FirstOrDefault(e => e.EmployeeID == id),
                Departments = employeeRepository.Departments.ToList()
            };
            return View(viewModel);
        }

        [HttpPost]
        public ActionResult Edit(EEmployee employee)
        {
            if (ModelState.IsValid)
            {
                employeeRepository.Save(employee);
                TempData["SaveMessage"] = string.Format("{0} {1} has been saved successfully.",
                    employee.FirstName, employee.LastName);
                return RedirectToAction("List");
            }
            else
            {
                TempData["SaveMessage"] = string.Format("An error has occurred. {0} {1} was not saved.",
                    employee.FirstName, employee.LastName);
                return View(employee);
            }
        }

        public ViewResult Create()
        {
            return View("Edit", new VMEmployee { Employee = new EEmployee() });
        }

Open in new window

<tr>
                <td class="display-label">Department:</td>
                <td class="display-field">@Html.DropDownListFor(m => m.Employee.DepartmentID,
                    new SelectList(Model.Departments, "DepartmentID", "Name"))</td>
            </tr>

Open in new window

error.jpg
Keith1985Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Craig WagnerSoftware ArchitectCommented:
Your Create() method is returning a view model that doesn't have the Departments populated. When the view tries to create the DropDown the object is null.

            VMEmployee viewModel = new VMEmployee
            {
                Employee = new EEmployee(),
                Departments = employeeRepository.Departments.ToList()
            };
            return View(viewModel);
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Keith1985Author Commented:
Right on. Thank you very much.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Web Frameworks

From novice to tech pro — start learning today.