C
C#3y ago
nauvran

❔ 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
Angius
Angius3y ago
IME this error happens when some async calls are not awaited, or when you have an async void method somewhere That's usually the culprit
nauvran
nauvranOP3y ago
The 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)
Angius
Angius3y ago
Uh It's non-tracking And you use the result to update the records? Preventing that is explicitly the purpose of non-tracking queries
nauvran
nauvranOP3y ago
Yes I only add non tracking after getting the error as I thought that would fix it
Angius
Angius3y ago
Instead of UpdateRange, after you're done updating the items, just call SaveChangesAsync() on the context
var things = await _ctx.Things.ToListAsync();

foreach (var t in things)
{
t.Name = $"New Name {t.Name}";
}

await _ctx.SaveChangesAsync();
var things = await _ctx.Things.ToListAsync();

foreach (var t in things)
{
t.Name = $"New Name {t.Name}";
}

await _ctx.SaveChangesAsync();
nauvran
nauvranOP3y ago
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
Angius
Angius3y ago
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 lol
nauvran
nauvranOP3y ago
I only use them because it's what I've been taught Oh well, but really thanks a lot
Accord
Accord3y ago
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.

Did you find this page helpful?