❔ Ef tracking issue
I'm getting a "instance of entity cannot be tracked because another instance with the key value {productNo:10492} is already being tracked}"
I have asNoTracking on my dB call, I've tried to detach all entities but there are none
I've tried to remove as many relationships with the productNo as I can and nothing works
9 Replies
IME this error happens when some async calls are not awaited, or when you have an
async void
method somewhere
That's usually the culpritThe main dB call is awaited and the new smaller call I've made is also awaited
The only async void method isn't being used and I just removed the async part and tried again
So sadly not that easy a fix :/
Var test2 = await _appDbContext.Products.AsNoTracking.Where(x => x.LocationNo = containerToMoveFrom.Trolley.AssetType).ToListAsync()
Then I change some stuff like the locationNo to move the items
This is done via a foreach where I modify the list of objects from above linq
Then I simply use _appDbContext.UpdateRange(products)
Uh
It's non-tracking
And you use the result to update the records?
Preventing that is explicitly the purpose of non-tracking queries
Yes
I only add non tracking after getting the error as I thought that would fix it
Instead of
UpdateRange
, after you're done updating the items, just call SaveChangesAsync()
on the context
Worth a shot
Give me a moment
Huh that worked
How come update range broke it completely?
Thanks a lot ZZZ
I've spent all day stuck on this issue trying different things
Update()
and UpdateRange()
also attach detached entities, or even completely unrelated ones, so something might've gone wrong there, dunno
I never use them tbh
And, seeing how it was the culprit, I'd say don't use them either lolI only use them because it's what I've been taught
Oh well, but really thanks a lot
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.