I have a question about how EntityFramework works because it's doing something odd in an application I am developing. In a nutshell, I am adding a child entity (a report) to a parent entity (a project), saving it to the database, then when I attempt to retrieve it, the child entity (the report) is not there in the parent entity (the project).
Here are the more detailed steps of what I'm doing:
public JsonResult SubmitData(int projectId, string data = null)
Project project = _projectService.GetProject(projectId);
Report report = CreateReport(data);
project.Report.Add(report);
_projectService.UpdateProjectForReport(project);
// Rest of code omitted...
}
public class ProjectService : IProjectService
{
public void UpdateProjectForReport(Project project)
{
_context.SaveChanges();
}
// Rest of code omitted...
}
^ The above code gets run after the user fills out some information on a form and clicks submit. The information gets passed to SubmitData(...) as a json string called "data". The project to which the report is to be saved is retrieved, the json data is converted to a report, the report is added to the project, and the changes to the project are saved to the database.
I have confirmed that the report is in fact saved to the database and is associated with the project.
Then next step involves retrieving the report:
public async Task<HttpResponseMessage> GetTop3ReportCard([FromUri] int
projectId, [FromUri] int reportId = 0)
{
_project = _projectService.GetProject(projectId);
Report report = _project.Report.Where(r => r.ReportId == reportId).FirstOrDefault();
// Rest of code omitted...
}
But report is always null.
I've verified that reportId in the call to GetTop3ReportCard(...) is not 0. Neither is projectId.
The only way around this is to restart the application in Visual Studio. Once I do that, and then try to retrieve my report, it comes back not null.
But why would an entity like Project not be loaded by EntityFramework with all the reports belonging to it once they are saved to the database? Is there something about the way EntityFramework works that I don't know about here?