3

出于审核日志记录的目的,我覆盖SaveChanges()了 EF 4.1 Database-First approach 中的方法。

我有所有 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
        }
    }
4

3 回答 3

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;
}
于 2012-01-16T06:38:57.990 回答
3

尝试使用ObjectStateEntry.EntityKeyEntityKey.EntityKeyValues

var keyValues = stateEntityEntry.EntityKey.EntityKeyValues;

它返回一个EntityKeyMember数组。然后,您可以使用KeyandValue属性,它们分别返回 astringobject

于 2012-01-16T06:53:44.353 回答
0

这是我的扩展方法形式的解决方案。

public static class ExtensionMethods
{
    public static IReadOnlyDictionary<string, object> GetKeyValues(this ObjectStateEntry instance)
    {
        var keyMemberNames = instance
            .EntitySet
            .ElementType
            .KeyMembers
            .Select(x => x.Name)
            .ToList();

        var currentValues = instance.CurrentValues;
        var result = new Dictionary<string, object>();
        for (var i = 0; i < currentValues.FieldCount; i++)
        {
            var name = currentValues.GetName(i);
            if (!keyMemberNames.Contains(name))
                continue;

            var value = currentValues.GetValue(i);
            result.Add(name, value);
        }

        return result;
    }

    public static IReadOnlyDictionary<string, object> GetValues(this ObjectStateEntry instance)
    {
        var currentValues = instance.CurrentValues;
        var result = new Dictionary<string, object>();
        for (var i = 0; i < currentValues.FieldCount; i++)
        {
            var name = currentValues.GetName(i);
            var value = currentValues.GetValue(i);
            result.Add(name, value);
        }

        return result;
    }
}
于 2021-11-03T13:36:21.253 回答