从Entity Framework中的ObjectStateEntry获取所有键及其值

Mos*_*afa 3 c# audit entity-framework entity-framework-4.1 ef-database-first

对于审计日志记录目的,我SaveChanges()在EF 4.1 Database-First方法中覆盖方法.

我有所有ObjectStateEntry对象,我想知道我是否可以从每个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
        }
    }
Run Code Online (Sandbox Code Playgroud)

nem*_*esv 7

我没有测试它,但这样的东西应该工作:

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;
}
Run Code Online (Sandbox Code Playgroud)