(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)
{
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