如何对表中数据的修改作历史记录

如今有一张表User数据库

里面字段以下this

UserID 用户账号(惟一不可修改)spa

UserName 用户名blog

Phone 手机号get

Email 邮箱string

CreateTime 建立时间it

UpdateTime 更新时间io

比较low的方式是创建一个记录表User_Recordevent

一样包含以上字段,每次修改插入一条修改以前的记录,这样有两个弊端class

1.数据冗余,及时至修改了一个字段也要插入一整条记录

2.不利于扩展,若是主表新增字段,记录表User_Record也要相应增长,违背了DRY原则

因此,在此提出一个相对优秀的解决方案

新建一个UpdateEvent表,有以下字段

EVENT_ID 自增ID

VERSION 版本号

OBJECT_TYPE 源数据的表名或者能惟一对应的源数据表的标识都可(能够看到此表支持多表进行扩展)

固然,也可根据业务需求自行定义类别

OBJECT_ID 源数据表主键

FIELD_NAME 修改的源数据表的字段名

OBJECT_CODE 源数据表主键对应的CODE(能够忽略)

FIELD_OLD_VALUE 该字段原来的值

FIELD_NEW_VALUE 该字段最新的值



每次咱们进行更新操做的时候,首先获取修改以前的实体oldUser和修改以后的newUser

而后经过反射进行两个版本的比较,得到AuditData列表插入到数据库

public class AuditData
    {
        public  string EVENT_ID {get;set;}

        public string VERSION  {get;set;}

        public string OBJECT_TYPE  {get;set;}

        public string OBJECT_ID  {get;set;}

        public string OBJECT_CODE  {get;set;}

         public string FIELD_NAME  {get;set;}

         public string FIELD_OLD_VALUE  {get;set;}

         public string FIELD_NEW_VALUE  {get;set;}

 List<AuditData> auditDataList = new List<AuditData>();
            PropertyInfo[] userPropertys = newUser.GetType().GetProperties();
            for (int i = 0; i < userPropertys.Length; i++)
            {
                SorMember sor = SorMemberFactory.GetSorMember(userPropertys[i]);
                if (!sor.HaveMapAttribute)
                {
                    string propertyName = userPropertys[i].Name;
                    string newPropertyValue = Convert.ToString(userPropertys[i].GetValue(newUser, null));
                    if (version == "1")
                    {
                        if (!string.IsNullOrEmpty(newPropertyValue))
                        {
                            AuditData auditData = new AuditData(eventId, version, "USER", newUser.UserId, newUser.UserUid, this.GetFieldName(newUser.GetType(), propertyName), string.Empty, newPropertyValue);
                            auditDataList.Add(auditData);
                        }
                    }
                    else
                    {
                        string oldPropertyValue = this.GetPropertyValue(oldUser, propertyName);
                        if (newPropertyValue != oldPropertyValue)
                        {
                            AuditData auditData = new AuditData(eventId, version, "USER", newUser.UserId, newUser.UserUid, this.GetFieldName(newUser.GetType(), propertyName), oldPropertyValue, newPropertyValue);
                            auditDataList.Add(auditData);                        }                    }                }            }