entity framework does not load navigation property after adding object

c# entity-framework entity-framework-6

Question

I have MVC project and EF6 model.

enter image description here

LazyLoading is enabled. In controller I have the following action

    public ActionResult AddStage(int projectId, int employeeId)
    {
        using(var context = new TestProjectEntities())
        {
            var project = context.Projects.Find(projectId);
            if (project != null)
            {
                var stage = new Stage() {EmployeeID = employeeId, StageType = 1};
                project.Stages.Add(stage);
                context.Stages.Add(stage);
                context.SaveChanges();
            }

            ListEmployees(project);
        }

        return Redirect("Index");
    }

    private void ListEmployees(Project project)
    {
        var names = new List<string>();
        foreach(var stage in project.Stages)
        {
            if (stage.Employee != null)
            {
                names.Add(stage.Employee.Name);
            }
        }
    }

But in ListEmployees method stage.Employee == null in foreach statement. Why?

And if i call AddStage for second time then stage.Employee != null in ListEmployee

1
3
8/6/2015 1:59:23 PM

Accepted Answer

That's because you're simply setting the foreign-key property (Stage.EmployeeID) without setting the navigation-property (Stage.Employee).

Usually, after calling SaveChanges(), EF would update the navigation property as well. But, since the Stage object is created manually by you it's not tracked (using a DynamicProxy) and you'll have to explicitly fix-up the relationship:

context.Entry(stage).Reference(c => c.Employee).Load();

Another approach would be to fetch the Employee and use it instead of setting the foreign-key property:

var employee = context.Employees.Find(employeeId);
var stage = new Stage() { Employee = employee, StageType = 1};

See MSDN

9
8/6/2015 2:14:30 PM

Popular Answer

new Stage()

Don't do this with EF objects. You won't get the correct proxy object that can lazy load navigation properties. You need to use something like dbContext.Set<Stage>().Create()



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow