Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell if any entities in context are dirty with .Net Entity Framework 4.0

Tags:

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.

  1. I would prefer a single function to call to see if any entities are unsaved instead of looping though all entities in the context.
  2. I can't figure out how to detect entities I have added. This suggests to me that I do not fully understand how the entity context works. For example, if I have the ObjectSet myContext.Employees, and I add a new employee to this set (with .AddObject), I do not see the new entity when I look at the ObjectSet and I also don't see the .Count increase. However, when I do a context.SaveChanges(), my new entity is persisted...huh?

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.

like image 734
Mike Gates Avatar asked Apr 26 '10 15:04

Mike Gates


People also ask

What is Entitystate in Entity Framework?

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.

What are the three types of Entity Framework?

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.

What disconnected entities?

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.


2 Answers

var addedStateEntries = Context     .ObjectStateManager     .GetObjectStateEntries(EntityState.Added); 
like image 99
Craig Stuntz Avatar answered Oct 16 '22 09:10

Craig Stuntz


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();     } } 
like image 29
Jo VdB Avatar answered Oct 16 '22 08:10

Jo VdB