Search code examples
c#entity-frameworkentity-framework-4.1auditef-database-first

Getting all keys and their values from ObjectStateEntry in Entity Framework


For audit logging purpose I override SaveChanges() method in EF 4.1 Database-First approach .

I have all ObjectStateEntry object and I'm wondering if I could get all keys and their values from each ObjectStateEntry .

   IEnumerable<ObjectStateEntry> changes = this.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Deleted | EntityState.Modified);
    foreach (ObjectStateEntry stateEntryEntity in changes)
    {
        if (!stateEntryEntity.IsRelationship &&
                stateEntryEntity.Entity != null &&
                    !(stateEntryEntity.Entity is DBAudit))
        {
          list<object , object> KeyValues = GetAllKeyValues(stateEntryEntity );
          //Do log all keyvalues
        }
    }

Solution

  • I haven't tested it but something like this should work:

    private Dictionary<string, object> GetAllKeyValues(ObjectStateEntry entry)
    {
        var keyValues = new Dictionary<string, object>();
        var currentValues = entry.CurrentValues;
        for (int i = 0; i < currentValues.FieldCount; i++)
        {
            keyValues.Add(currentValues.GetName(i), currentValues.GetValue(i));
        }
        return keyValues;
    }