I have MVC project and EF6 model.
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
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
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()