Created
February 4, 2013 16:57
-
-
Save cerebrate/4707957 to your computer and use it in GitHub Desktop.
Checking for a dirty context using entity framework.
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment