Detaching specific objects using Entity Framework before SaveChanges

D

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.

[code]
// 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);
}
}
[/code]

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.

About the author

By Jamie

My Books