I think the problem is that as far as the context is concerned, you haven’t actually changed anything.
You can use the lazy loading approach previously suggested by using virtual
, but since you haven’t requested that the Employee be loaded yet, it’s still null. You could try this:
var forceLoad = project.Employee;
project.Employee = null; // Now EF knows something has changed
Context.SaveChanges();
Alternatively, explicitly include it in your original request:
var project = Context.Projects.Include(x => x.Employee).FirstOrDefault(x => x.ProjectId == projectId);
project.Employee = null;
Context.SaveChanges();
On a side note, FirstOrDefault
will return null
if no Project
matches the given id. If you know the project exists, you can just use First
. You could even use Single
which will assert that there is only one such project. If you continue to use FirstOrDefault
, I’d recommend checking for null
before working with project
.