Entity Framework: Checking for a dirty context
Another repost from the blog of yore (-10 years).
The quick way to check if you need to SaveChanges() your database context, and/or prompt the user whether or not they want to save changes:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /// <summary> | |
| /// Detect whether the context is dirty (i.e., there are changes in entities in memory that have | |
| /// not yet been saved to the database). | |
| /// </summary> | |
| /// <param name="context">The database context to check.</param> | |
| /// <returns>True if dirty (unsaved changes); false otherwise.</returns> | |
| public static bool IsDirty(this DbContext context) | |
| { | |
| Contract.Requires<ArgumentNullException>(context != null); | |
| // Query the change tracker entries for any adds, modifications, or deletes. | |
| IEnumerable<DbEntityEntry> res = from e in context.ChangeTracker.Entries() | |
| where e.State.HasFlag(EntityState.Added) || | |
| e.State.HasFlag(EntityState.Modified) || | |
| e.State.HasFlag(EntityState.Deleted) | |
| select e; | |
| if (res.Any()) | |
| return true; | |
| return false; | |
| } |
(If you don’t use code contracts, you’ll need to replace that Contract.Requires line with your favorite null check.)
