Change Tracking and some errors..
I recently got a ticket to fix a module and I encounter an error related that can be solve by Change Tracker API. I'm glad that I encounter these kind of errors, it teaches me.
It says entity type cannot be tracked because another instance with the key value is already being tracked.
Let's take a look at the codebase. For context we got two repository layer because we are dealing with 2 seperate databases here a parent and a child.
The error happens we we try to update the instance that is already being tracked .
Here we can see that the GetByID already tracked the proformaEntryDetails
And after that line the real logic on updating the details will come, so after tracking entities that are already being tracked and updating that entities that are being tracked again then the error will throw.
There are two solutions here one
1.) To modify the GetById which is the more sensible because on our architecture clean code we are using repositories for the seperation of concerns. So by creating another getById there would be enough.
2.) Is to detach the tracked entity on the getById before updating. Which I will be providing examples on how to do it.
By detaching the existing ID on the details (child) and updating it.
The .Local shows the entities that is being tracked.
Here you can try to use a debugger to check if the entity that is being tracked that is causing the error will be detached to your local.
That's all and I hope I helped someone to debug today.
Subscribe to my newsletter
Read articles from Juan Miguel Nieto directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Juan Miguel Nieto
Juan Miguel Nieto
A software developer trying to write organic blogs.