using System.Text;
using SqlSugar;
namespace DS.Module.SqlSugar;
///
/// sqlsuagr差异帮助类
///
public static class SqlSugarDiffUtil
{
///
/// 比较两个数据对象的修改内容
///
///
///
///
public static DiffLog GetDiff(List beforeData, List afterData)
{
string mianID = null;
if (beforeData != null)
{
var keyCoulumn = beforeData[0].Columns.FirstOrDefault(p => p.IsPrimaryKey == true);
if (keyCoulumn != null)
{
mianID = keyCoulumn.Value.ToString();
}
}
else if (afterData != null)
{
var keyCoulumn = afterData[0].Columns.FirstOrDefault(p => p.IsPrimaryKey == true);
if (keyCoulumn != null)
{
mianID = keyCoulumn.Value.ToString();
}
}
StringBuilder sb = new StringBuilder();
if (beforeData != null && afterData != null)
{
var befroeColumns = beforeData[0].Columns;
var afterCloums = afterData[0].Columns;
foreach (var item in befroeColumns)
{
if (IgnoreColumns.Contains(item.ColumnName))
continue;
var afterItem = afterCloums.FirstOrDefault(p => p.ColumnName == item.ColumnName && !p.Value.Equals(item.Value));
if (afterItem != null)
{
sb.Append($"[字段:{item.ColumnDescription},修改前:{item.Value},修改后:{afterItem.Value}]");
}
}
}
return new DiffLog { Id = mianID, DiffData = sb.ToString() };
}
public class DiffLog
{
///
/// 主键Id
///
public string Id { get; set; }
///
/// 差异数据
///
public string DiffData { get; set; }
}
///
/// 忽略的字段
///
private static readonly List IgnoreColumns = new List()
{
"CreateTime",
"CreateUserName",
"CreateBy",
"UpdateTime",
"UpdateUserName",
"UpdateBy",
"DeleteTime",
"DeleteUserName",
"DeleteBy",
};
}