Terry
Terry

Reputation: 842

Entity Framework - Create and use navigation property

I am using Entity Framework and .Net 4 MVC 3. In my create method on my controller I take in an employee object which I use to create the entry in my database.

public class Employee 
{
    public int Id { get; set; }
    public int ManagerId { get; set; }
    public virtual Employee Manager { get; set; }
}

public ActionResult Create(Employee model)
{
    if (ModelState.IsValid)
    {
        db.Employees.Add(model);
        db.SaveChanges();

        // Now I want to use the navigation properties
        Notification(model.Manager.Name);
    }
}

I post the manager Id back from the view. Now if I redirect back to the details page the manager has been created - however when I try and access it like the above it is null. What I have had to resort to is:

if (ModelState.IsValid)
{
    model.Manager = _employeeRepository.Get(model.ManagerId);
    db.Employees.Add(model);
    db.SaveChanges();

    // Now this works
    Notification(model.Manager.Name);
}

However this doesn't seem right. Surely EF creates the Manager object for me so why do I need to manually get and set it? Am I doing something wrong?

Upvotes: 1

Views: 288

Answers (1)

Ed Chapel
Ed Chapel

Reputation: 6932

Though it may seem wrong, that's the intended functionality and your solution is approximately correct. The EF DbContext won't grab the Manager property automatically because it could potentially be costly to do that. If it did it automatically and did not want that, you'd be angry with EF. The answer (and your original solution) is to explicitly get the data on a subsequent call.

I would suggest a slightly different implementation:

if (ModelState.IsValid)
{
    db.Employees.Add(model);
    db.SaveChanges();

    // Get the manager name only after the SaveChanges is successful
    // Will fail if the manager ID is not valid
    var managerName = db.Managers.Where(mgr => mgr.ManagerId == model.ManagerId).Select(mgr => mgr.Name).Single();
    Notification(managerName);
}

Upvotes: 2

Related Questions