I went through this answer, but it still gave me the same exception. My DbContext
has Configuration.AudoDetectChangesEnabled = false
and Configuration.LazyLoadingEnabled = true
, in case that makes a difference. For a simple example, consider the following:
public class Employee {
public int Id {get;set;}
public int TitleId {get;set;}
[ForeignKey(nameof(Employee.TitleId))]
public virtual Title Title{get;set;}
}
Query is done with Context.Set<Employee>().Include(nameof(Employee.Title))
. In my case, I have an existing Employee
with an existing Title
. I've updated my entity with a new TitleId
, one that already exists in the database. Then, I update the EntityState
to EntityState.Modified
and call SaveChanges()
. This gives the following Exception
:
A referential integrity constraint violation occurred: The property value(s) of 'Employee.TitleId' on one end of a relationship do not match the property value(s) of 'Title.Id' on the other end.
Okay, so that should be due to a mismatch between the foreign key id and the navigation property. So then I set Title
to null
prior to setting EntityState
. Still the same issue.
Next, I've tried detaching the entity prior to setting EntityState.Modified
. Now, saving the entity works, but when I try to load it again, I get a NullReferenceException
on the navigation property.
What's the proper way to do this?