用户活动日志使用MVC记录旧值和新值

时间:2017-05-16 10:51:32

标签: c# asp.net-mvc

我的任务是记录项目用户的用户活动。因此要求是将所有更改记录到数据库中,即。必须记录对数据库的任何更新。

示例:

  

User1(假定为admin)尝试更新firstname,lastname   然后我应该记录以下消息:User1已更新   来自" oldValue"的user2的名字到" newValue"

我正在使用 MVC entityframework log4net 来记录用户活动。

由于我使用模型填充我的视图,我可以获得旧模型和新模型。但是,我如何比较模型并找出差异来记录它?

我首先想到我可以覆盖类的Equal方法,但是他的equ等方法返回一个bool值,它只会给我真或假。

但我想知道旧的和新的价值观。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

我设法通过遍历类中的每个属性来解决它,并从两个对象中获取属性的值并进行比较。

以下是代码:

Type types = typeof(ModelName);

//Loop through each properties inside class and get values for the property from both the objects and compare
foreach (System.Reflection.PropertyInfo property in types.GetProperties())
{
    string newValue = string.Empty;
    string oldValue = string.Empty;
    if (types.GetProperty(property.Name).GetValue(modelnew, null) != null)
        newValue = types.GetProperty(property.Name).GetValue(modelnew, null).ToString();
    if (types.GetProperty(property.Name).GetValue(modelOld, null) != null)
        oldValue = types.GetProperty(property.Name).GetValue(modelOld, null).ToString();

    if (newValue.Trim() != oldValue.Trim()) //if both values are not same
    {
        if (!string.IsNullOrEmpty(newValue.Trim()) && !string.IsNullOrEmpty(oldValue.Trim()))//if both values are not null
        {
            //log the update ie. value is updated from oldValue to newValue
        }
        else if (!string.IsNullOrEmpty(oldValue.Trim()))//else if only oldvalue is not null
        {
            //log - oldvalue has been deleted for property.name
        }
        else if (!string.IsNullOrEmpty(newValue.Trim()))
        {
            //log- newValue has been added for property.name
        }
    }
}