I want to be able to tell if there is any unsaved data in an entity framework context. I have figured out how to use the ObjectStateManager to check the states of existing entities, but there are two issues I have with this.
I have been unable to find an answer to this in my msdn searches, so I was hoping someone here would be able to clue me in.
Thanks in advance.
EF API maintains the state of each entity during its lifetime. Each entity has a state based on the operation performed on it via the context class. The entity state represented by an enum System.
There are three approaches to model your entities in Entity Framework: Code First, Model First, and Database First. This article discusses all these three approaches and their pros and cons.
Entities that are not being tracked by a context are known as 'disconnected' entities. For most single-tier applications, where the user interface and database access layers run in the same application process, you will probably just be performing operations on entities that are being tracked by a context.
var addedStateEntries = Context .ObjectStateManager .GetObjectStateEntries(EntityState.Added);
Via extension method (for every ObjectContext):
internal static class ObjectContextExtensions { public static bool IsContextDirty(this ObjectContext objectContext) { return objectContext .ObjectStateManager .GetObjectStateEntries( EntityState.Added | EntityState.Deleted | EntityState.Modified).Any(); } }
or via partial method (only for your ObjectContext):
partial class MyModel { public bool IsContextDirty() { return ObjectStateManager .GetObjectStateEntries( EntityState.Added | EntityState.Deleted | EntityState.Modified).Any(); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With