Domanda

A scopo di registrazione dell'audit, sostituisco il metodo SaveChanges() nell'approccio Database-First EF 4.1.

Ho tutti gli oggetti ObjectStateEntry e mi chiedo se potrei ottenere tutte le chiavi e i relativi valori da ogni 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
        }
    }
È stato utile?

Soluzione

Non l'ho testato ma qualcosa del genere dovrebbe funzionare:

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

Altri suggerimenti

Prova a utilizzare ObjectStateEntry.EntityKey e EntityKey.EntityKeyValues :

var keyValues = stateEntityEntry.EntityKey.EntityKeyValues;

che restituisce un array di EntityKeyMember .È quindi possibile utilizzare le proprietà Key e Value, che restituiscono rispettivamente un string e object.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top