In previous article, we have seen what a keyless entity means and how to declare a keyless entity. In this article, let’s discuss about a related concept – identity resolution.
What is it ?
When any entity is updated / added / deleted, EF Core context tracks the entities. Entities can be tracked by DbContext only if that entity has primary key. That means, if an entity is a keyless entity, then it cannot be tracked by DbContext.
But the question is, how does DbContext tracks those entities ? Can it track multiple objects which have same primary key ?
A DbContext can track only one instance of a given primary key. This means multiple instances of an entity with the same key value must be resolved to a single instance.
In order to understand this concept, let’s create a demo. We will use our blog app’s BaseRepository for this experiment. Below code shows an Update method. It first retrieves a record with given ID. Then it creates a new object with same ID and some new values.
If we try to use this object in the Update call, then it throws an exception:
We just have seen a single case in above code, which generates ‘Entity is already being tracked’ error. There can be other things in code or design which may cause this error. For example, if the primary key is not being auto generated, this error may be raised multiple times by the application. Or if the DbContext implementation is reused for multiple unit of works, then also this type error can be raised by EF core.
Why Identity Resolution Is Needed ?
EF Core tracks single instance for a given primary key value. It is because of two things:
- Multiple instances, although they have same primary key value, may have different relationships with related data. This might cause a confusion of identifying which relationship representation is correct.
- Multiple instances may have different data for one or more properties other than primary key. Thus, it would be difficult for EF Core to understand which properties are changed and which are not and which properties should be used while updating database.
So, that’s it for today’s post. Thanks for reading this.
I hope you find above information helpful. Let me know your thoughts.