在各种管理系统中经常需要展示某条数据的过往变更记录,更清晰的展示该条数据的历史过程,也能更直观的追溯是谁变更了数据。数据变更往往会调用Update方法实现更新部分数据,可以在Update时使用反射对比新老数据的值,将变更的数据写入变更记录表中。
// 忽略对比字段
List<string> ignoreColumnList = new List<string> {
"Id",
"TypeId",
"StatusId",
"CreatedTime",
"UpdatedTime",
"CreatedUserId",
"CreatedRealName",
"CreatedUserName",
"UpdatedUserId",
"UpdatedUserName",
"IsDeleted"
};
Record record = new Record();
List<RecordData> recordDataList = new List<RecordData>();
record.TableId = entity.Id;
record.TableName = "Project";
record.OpName = "编辑";
record.Id = YitIdHelper.NextId();
record.CreatedUserId = long.Parse(userId);
record.CreatedUserName = userName;
string oldValue = "";
string newValue = "";
//通过反射获取编辑后实体的属性列表
var propertyList = entity.GetType().GetProperties();
foreach (var property in propertyList)
{
//如果name在忽略字段列表中就跳过判断
if (ignoreColumnList.Contains(property.Name))
{
continue;
}
//如果值相同也跳过
if (property.GetValue(entity) == property.GetValue(oldEntity))
{
continue;
}
//获取字段的注释内容,方便前台展示
object[] objs = property.GetCustomAttributes(typeof(CommentAttribute), true);
string commentText = "";
if (objs.Length > 0)
{
commentText = ((CommentAttribute)objs[0]).Comment;
}
oldValue = "";
newValue = "";
if (property.GetValue(oldEntity) != null)
{
oldValue = property.GetValue(oldEntity) + "";
}
if (property.GetValue(entity) != null)
{
newValue = property.GetValue(entity) + "";
}
if (oldValue == newValue)
{
continue;
}
//特殊字段的处理
//处理关联表、字典值等内容
if (property.Name == "OrganizerTitle")
{
//
//oldValue = 特殊取值
//newValue = 特殊取值
}
RecordData recordData = new RecordData
{
Id = YitIdHelper.NextId(),
RecordId = record.Id,
Field = property.Name,
FieldName = commentText,
OldValue = oldValue,
NewValue = newValue
};
//保存详细的变更内容
recordDataList.Add(recordData);
}
正文完