Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Checking for a dirty context using entity framework.
/// <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) ||
select e;
if (res.Any())
return true;
return false;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment