EF通过反射追踪修改记录.适合记录变更系统

本文介绍了一种用于记录对象属性变更的方法,通过比较旧对象与新对象的属性值来记录哪些属性发生了变化,并将变更信息存入历史表中。此方法适用于需要跟踪数据变更的应用场景。
private static void IsUpdate<T>(T old, T current, string id)
        {
            Model.PerFileHistory history = new Model.PerFileHistory();
            Model.Atrributes.ModifyFields atrr = null;
            Type type = typeof(T);
            PropertyInfo[] propertys = type.GetProperties();
            foreach (PropertyInfo property in propertys)
            {
                if (property.PropertyType.IsValueType || property.PropertyType.Name == "String")
                {
                    if (property.PropertyType.FullName.Contains("Guid"))
                        continue;
                    //if (property.Name != "CreateUserID" && property.Name != "CreateTime" && property.Name != "ModifyUserID" &&                                    property.Name != "LastModifyTime")//排除这些字段不做判断
                    //{
                    if (property.GetCustomAttributes(typeof(Model.Atrributes.ModifyFields), false).Count() > 0)
                    {
                        object o1 = property.GetValue(old, null); //以前的值
                        object o2 = property.GetValue(current, null); //修改后的值
                        string str1 = o1 == null ? string.Empty : o1.ToString();
                        string str2 = o2 == null ? string.Empty : o2.ToString();
                        //判断两者是否相同,不同则插入历史表中
                        if (str1 != str2)
                        {
                            history.BeforeValue = str1; //修改前的值
                            history.AfterValue = str2; //修改后的值
                            history.PCardNo = id; //修改数据的ID
                            history.IPAddress = HanNeng.Common.GetClientIP.GetRealIP(); //获取当前用户的IP地址
                            atrr = property.GetCustomAttributes(typeof(Model.Atrributes.ModifyFields), false)[0] as                    Model.Atrributes.ModifyFields;
                            history.ModifyField = property.Name;  //修改的字段名称
                            history.ModifyFieldName = atrr.FieldsName; //修改的字段中文名称

                            new BLL.PerFileHistory().AddModel(history);
                        }
                    }
                    //}
                }
            }
        }

  

转载于:https://www.cnblogs.com/toloe/p/7018538.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值