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