本文主要是介绍如何对表中数据的修改做历史记录,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
现在有一张表User
里面字段如下
UserID 用户帐号(唯一不可修改)
UserName 用户名
Phone 手机号
Email 邮箱
CreateTime 创建时间
UpdateTime 更新时间
比较low的方式是建立一个记录表User_Record
同样包含以上字段,每次修改插入一条修改之前的记录,这样有两个弊端
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);
}
}
}
}
这篇关于如何对表中数据的修改做历史记录的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!