The problem:
I have the code which is adding/updating properties with EF. Previously it was calling after modifying each property SaveChanges() and in that case it was working. What I have done. I have modified the code to have a batch (10 items at this time) and after inserting number of entries call SaveChanges(). But sometimes it starts to throw such an exception
A referential integrity constraint violation occurred: The property values that define the referential constraints are not consistent between principal and dependent objects in the relationship.
Issue I found:
The issue I found when I tried to modify 14 entries. First batch of 10 entries it is doing good. Than it is adding 11th entry and when tries to add 12th it was throwing this exception. I checked the code and found part which is causing exception.
property.CountryId = importProperty.CountryId;
It is setting CountryId to 123, but navigation property Country here has Id set to 54 (I am not changing this, just got version from database). Setting navigation property to null manually is throwing such an error
The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.
Question:
What should I do? Why it is working when I'm calling SaveChanges after each entry and not working in this case? I found questions in Stackoverflow about this problem, but no one solves my issue.
Some code:
public void InsertOrUpdateEntity(TEntity entity)
{
if (entity.ObjectState == ObjectState.Added)
{
dbSet.Add(entity);
}
else
{
dbSet.Attach(entity);
context.ApplyStateChanges();
}
}
Error occured on the line dbSet.Attach(entityGraph);
with a property mentioned above.