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