Skip to content

Instantly share code, notes, and snippets.

@cerebrate
Created February 4, 2013 16:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cerebrate/4707957 to your computer and use it in GitHub Desktop.
Save cerebrate/4707957 to your computer and use it in GitHub Desktop.
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) ||
e.State.HasFlag(EntityState.Deleted)
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