Last Updated: February 25, 2016
·
6.98K
· cerebrate

Check for a dirty context in Entity Framework

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:

/// <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.)