Question

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
        }
    }
Was it helpful?

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;
}

OTHER TIPS

Try using ObjectStateEntry.EntityKey and EntityKey.EntityKeyValues:

var keyValues = stateEntityEntry.EntityKey.EntityKeyValues;

which returns an array of EntityKeyMember. You can then use the Key and Value properties, which return a string and object respectively.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top