加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 显示原始值实体框架7

发布时间:2020-12-16 00:25:51 所属栏目:百科 来源:网络整理
导读:我有一个审计表,跟踪添加,删除和修改.我在实体框架内跟踪这个而不是使用数据库触发器有多种原因,但实际上是因为我们使用了一个进程账户,我想跟踪用户实际对该记录进行了哪些更改. 我有这个与EF 5我不记得我可能也曾在EF6中工作过.无论哪种方式,我都在用EF 7
我有一个审计表,跟踪添加,删除和修改.我在实体框架内跟踪这个而不是使用数据库触发器有多种原因,但实际上是因为我们使用了一个进程账户,我想跟踪用户实际对该记录进行了哪些更改.

我有这个与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()
         }
         );
      }
 }

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

解决方法

// 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}");
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读