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

后端 未结 4 952
感情败类
感情败类 2020-12-14 18:07

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 e

相关标签:
4条回答
  • 2020-12-14 18:13

    This article describes exactly what is needed to perform Change Tracking in the Entity Framework:

    Identity Resolution, State Management, and Change Tracking (Entity Framework) - MSDN

    0 讨论(0)
  • 2020-12-14 18:17
    var addedStateEntries = Context
        .ObjectStateManager
        .GetObjectStateEntries(EntityState.Added);
    
    0 讨论(0)
  • 2020-12-14 18:17

    A simple way to get a reusable single method/property you could add a new method to your ObjectContext by creating a partial class and adding a property like this:

    public partial class MyEntityContext
    {
      public bool IsContextDirty
      {
        get
        {
          var items = ObjectStateManager.GetObjectStateEntries(EntityState.Added);
          if(items.Any())
            return true;
          items = ObjectStateManager.GetObjectStateEntries(EntityState.Deleted);
          if (items.Any())
            return true;
          items = ObjectStateManager.GetObjectStateEntries(EntityState.Modified);
          if(items.Any())
            return true;
          return false;
        }
      }
    }
    

    Depending on what your looking for you could expose other properties to know if there are just deletes or modifications. This method could be simplified, but I wanted it to be clear what you would need to do.

    0 讨论(0)
  • 2020-12-14 18:32

    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();
        }
    }
    
    0 讨论(0)
提交回复
热议问题