显示原始值实体框架7

kev*_*n c 3 .net c# entity-framework entity-framework-core

我有一个审计表,跟踪添加,删除和修改.我在实体框架内跟踪这个而不是使用数据库触发器有多种原因,但实际上是因为我们使用了一个进程账户,我想跟踪用户实际对该记录进行了哪些更改.

我有这个与EF 5合作,我不记得我可能已经在EF6工作了.无论哪种方式,我都在用EF 7试图捕获原始值时遇到最困难的时间.

我注意到,当我在观察时 - 我可以看到非公开成员内部的原始价值 - 所以在我的脑海里,我知道它必须存在于某个地方.

最终这适用于EF早期版本:

EntityEntry dbEntry; //this is actually passed in a different area just showing as an example.

foreach (string propertyName in dbEntry.OriginalValues.PropertyNames)
{
    // For updates, we only want to capture the columns that actually changed
    if (!object.Equals(dbEntry.OriginalValues.GetValue<object>(propertyName), dbEntry.CurrentValues.GetValue<object>(propertyName)))
    {
        result.Add(new TableChange()
        {
            AuditLogID = Guid.NewGuid(),
            UserID = userId,
            EventDateUTC = changeTime,
            EventType = "M",    // Modified
            TableName = tableName,
            RecordID = dbEntry.OriginalValues.GetValue<object>(keyName).ToString(),
            ColumnName = propertyName,
            OriginalValue = dbEntry.OriginalValues.GetValue<object>(propertyName) == null ? null : dbEntry.OriginalValues.GetValue<object>(propertyName).ToString(),
            NewValue = dbEntry.CurrentValues.GetValue<object>(propertyName) == null ? null : dbEntry.CurrentValues.GetValue<object>(propertyName).ToString()
         }
         );
      }
 }
Run Code Online (Sandbox Code Playgroud)

我得到的错误是EntityEntry不包含OriginalValues的定义.我要拔掉头发......如何从EF 7的修改对象中获取原始值?

Sta*_*ams 12

// using System.Reflection;
foreach (var property in dbEntry.Entity.GetType().GetTypeInfo().DeclaredProperties)
{
    var originalValue = dbEntry.Property(property.Name).OriginalValue;
    var currentValue = dbEntry.Property(property.Name).CurrentValue;
    Console.WriteLine($"{property.Name}: Original: {originalValue}, Current: {currentValue}");
}
Run Code Online (Sandbox Code Playgroud)

  • @Hopeless,是的.这称为[String Interpolation](https://msdn.microsoft.com/en-us/library/dn961160.aspx). (3认同)
  • 与往常一样,建议进行错误处理.如果实体类包含未包含在模型中的属性,那么`dbEntry.Property(property.Name)`将抛出InvalidOperationException,例如通过[this]中显示的`[NotMapped]`注释(http:// ef.readthedocs.org/en/latest/modeling/included-properties.html).如果您只想考虑模型中映射的属性,则可以循环遍历`entry.Metadata.GetProperties()`.这可能也适用于[影子属性](http://ef.readthedocs.org/en/latest/modeling/shadow-properties.html),但我没试过. (2认同)