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. I also invite you to share and subscribe to the newsletter by using the buttons below! Cheers  😉

How useful was this post?

Click on a star to rate it!

Average rating 5 / 5. Vote count: 3

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Leave a Reply

Notify of