Database operation expected to affect
In EF Core, there is a rule that is not obvious about setting the primary key on child entities and adding it to the parent when the parent entity has already been saved (or retrieved from the context).
- When creating a parent entity that is not saved, when you add a child entity where you are manually setting the primary key, you will not see this behavior.
- The issue is that when a parent entity is already saved, when you try to add a child entity to it and set the primary key on it, EF will expect that child entity to already exist in the db. We are seeing this in certain cases because we are using a Guid for the primary key and are setting that key on entities often in cases where it doesn’t need to be. The symptom is that EF core will throw an exception
'Database operation expected to affect 1 row(s) but actually affected 0 row(s). Data may have been modified or deleted since entities were loaded.'
- The fix is to not set the primary key on the child entity.
In some cases it seems that in the same logic flow the primary key is needed, maybe to publish a message for example. The right way to deal with that is to actually change the entity to use an int for the primary key. The previous property that was the primary key should stay as a resource id.
In a pinch, if you can’t make the change to the primary key and have to set the primary key on the child entity, you can add the child entity to the database context first, then add it to the parent.
var entity = context.Customers.Add(customer);
- The issue is that when a parent entity is already saved, when you try to add a child entity to it and set the primary key on it, EF will expect that child entity to already exist in the db. We are seeing this in certain cases because we are using a Guid for the primary key and are setting that key on entities often in cases where it doesn’t need to be. The symptom is that EF core will throw an exception