EF doesn't have any direct "reject changes" operation. You can go through entity entries in ChangeTracker
/ ObjectStateManager
and overwrite current values with original values for modified entities. You can also detach added entities and change deleted entities back to unchanged but that all will mostly work only if you (or EF internally) didn't change the state of any independent association (relation). If you work with relations as well the whole thing can become much more complicated because you must revert relations as well - in such case it is simpler to reload data.
For reverting changes in DbContext API you can try this:
foreach (var entry in context.ChangeTracker
.Entries<YourEntityType>()
.Where(e => e.State == EntityState.Modified))
{
entry.CurrentValues.SetValues(entry.OriginalValues);
}
In this case I think the main problem is the way how you work with entities - you allow changes on live data and EF does its logic on behind to keep data consistent when changes are performed but later on you decide that those changes will not be saved. In this case you should do one of following:
- Discard changed data and reload whole data set (by recreating the context)
- Separate this logic to not work on live data and push data modification to EF context only when the modification is really confirmed
Context is doing something if you say it to do something. It never becomes busy itself.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…