November 21, 2024

EF Core detach all entities

Hey there folks, long time no post as I was pretty busy. I have many many ideas for blog posts, I just need to create some time to write them.

Recently I’ve had an issue with some entities and after performing a delete to the database. Basically, I was given this error while trying to update the entity:

System.InvalidOperationException: The instance of entity type 'Entity' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values

I personally don’t understand why an already tracked entity is not reused later if necessary. But this is an error that EF gives and I had to workaround a solution to detach any entity after the deletion, so I came up with this helper method:


public static void DetachAllEntries(this DbContext context)
{
    foreach (var entry in context.ChangeTracker.Entries().ToList())
    {
         context.Entry(entry.Entity).State = EntityState.Detached;
    }
}

So calling it after the deletion and then performing the update worked perfectly. This may not be needed in all situations, but in my case I didn’t have any other option.

This method can also be found in my nuget package Mindgaze.AspNetCore, version 1.3.1. Youhuu! So with this being said, I wish you happy coding!

Thanks for reading, I hope you found this article useful and interesting. If you have any suggestions don’t hesitate to contact me. If you found my content useful please consider a small donation. Any support is greatly appreciated! Cheers  😉

afivan

Enthusiast adventurer, software developer with a high sense of creativity, discipline and achievement. I like to travel, I like music and outdoor sports. Because I have a broken ligament, I prefer safer activities like running or biking. In a couple of years, my ambition is to become a good technical lead with entrepreneurial mindset. From a personal point of view, I’d like to establish my own family, so I’ll have lots of things to do, there’s never time to get bored 😂

View all posts by afivan →