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

标签 c# entity-framework entity-framework-4.1 audit ef-database-first

出于审计日志记录的目的,我重写了 EF 4.1 数据库优先方法中的 SaveChanges() 方法。

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

最佳答案

我还没有测试过,但像这样的东西应该可以工作:

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

关于c# - 从 Entity Framework 中的 ObjectStateEntry 获取所有键及其值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8876428/

相关文章:

c# - CTP5 EF Code First 与 Linq-to-sql

c# - EF中的主键最大值

c# - 匿名内部类在 Java 中作为键,但在 C# 中呢?

c# - 具有通用枚举的 HasFlag?

c# - 脚手架 Controller 不适用于 Visual Studio 2013 更新 3 和 4

entity-framework-4.1 - DbSet.Attach,它到底是做什么的?

wcf - 停止 WCF 将空 ICollection 反序列化为零容量阵列

entity-framework-4.1 - Entity Framework 4.0 中是否需要工作单元模式

c# - 在客户显示器上显示文本

c# - 对于WPF,免费烛台示例?