Detaching specific objects using Entity Framework before SaveChanges Detaching specific objects using Entity Framework before SaveChanges

Sometimes in large processes that span across multiple classes, it's possible that an entity is added to Entity Framework's context tracking. I've run into this scenario where we accidentally save things that get immediately deleted afterwards.

Let's look at a neat solution that will allow you to detach specific objects out of Entity Framework's context. In theory this can go in several places: In the code you know causes the entities to be added or before the call to SaveChanges. In this example we'll look at the latter because it is a nice and generic spot.



// Add to the constructor to create an event to call this function before SaveChanges happens
(Context as IObjectContextAdapter).ObjectContext.SavingChanges += ObjectContext_SavingChanges;
void ObjectContext_SavingChanges(object sender, EventArgs e)
{
var context = ((Context as IObjectContextAdapter).ObjectContext);
var newEntitiesWithId = context.ObjectStateManager.GetObjectStateEntries(EntityState.Added).ToList();
foreach (var newEntity in newEntitiesWithId)
{
// Add custom logic if you only want to remove entities based on specific conditions
context.Detach(newEntity);
}
}

The above code firstly adds a line of code that should go in your constructor for your Entity Framework context that will call the function ObjectContext_SavingChanges when SaveChanges is called.

Inside this function, I first get a list of entities that Entity Framework is considered new and will be inserted during save changes.

Instead I've injected some logic that will loop the list of new entities and when the condition matches my scenario where I don't want it to be in EntityState.Added I can call the Detach function that tells Entity Framework to not track this and don't insert it.

This is definitely not too common a process but can help in very specific scenarios where it is not easy to track down where an entity was added that shouldn't be saved.

Published on Jun 4, 2022

Tags: Entity Framework Tutorials For Beginners and Professionals | savechanges

Related Posts

Did you enjoy this article? If you did here are some more articles that I thought you will enjoy as they are very similar to the article that you just finished reading.

Tutorials

Learn how to code in HTML, CSS, JavaScript, Python, Ruby, PHP, Java, C#, SQL, and more.

No matter the programming language you're looking to learn, I've hopefully compiled an incredible set of tutorials for you to learn; whether you are beginner or an expert, there is something for everyone to learn. Each topic I go in-depth and provide many examples throughout. I can't wait for you to dig in and improve your skillset with any of the tutorials below.