检查实体字段是否被修改并记录修改内容

Dictionary<string, string> keyValueByFields = new Dictionary<string, string>();

keyValueByFields.Add("Doc_Name", "单证");
keyValueByFields.Add("Doc_Name2", "单证2");
keyValueByFields.Add("Marking_Name", "市场人员");
keyValueByFields.Add("BookingMan_Name", "订舱人");
keyValueByFields.Add("BusinessRisk_Remark", "业务风险备注");

public static Tuple<bool, string> CompareTypeFieldValue<T>(T newT, T oldT, Dictionary<string, string> keyValueByFields) where T : class
{
bool compareResult = true;
string compareMsg = string.Empty;

if (newT == null || oldT == null)
return new Tuple<bool, string>(compareResult, compareMsg);

PropertyInfo[] newProps = newT.GetType().GetProperties();
PropertyInfo[] oldProps = oldT.GetType().GetProperties();

foreach (var item in newProps)
{
ColumnAttribute column = item.GetCustomAttribute(typeof(ColumnAttribute)) as ColumnAttribute;
if (column != null && column.IsSQLColumn)
{
if (!column.IsPrimaryKey)
{
if (keyValueByFields.Keys.Contains(item.Name))
{
object newPropValue = item.GetValue(newT, null);
object oldPropValue = oldProps.FirstOrDefault(e => e.Name == item.Name).GetValue(oldT, null);

if (newPropValue == null)
newPropValue = string.Empty;

if (oldPropValue == null)
oldPropValue = string.Empty;

Type colType = item.PropertyType;
//当类型为Nullable<>时
if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>)))
{
colType = colType.GetGenericArguments()[0];
}

if (colType.Name.ToLower().StartsWith("decimal"))
{
if (string.IsNullOrWhiteSpace(newPropValue.ToString()))
newPropValue = "0.000";

if(string.IsNullOrWhiteSpace(oldPropValue.ToString()))
oldPropValue = "0.000";

decimal newD = decimal.Parse(newPropValue.ToString());
decimal oldD = decimal.Parse(oldPropValue.ToString());
if (newD != oldD)
{
compareResult = false;
compareMsg += keyValueByFields[item.Name] + "【" + oldPropValue + "】修改为【" + newPropValue + "】<br>";
}
}
else
{
if (newPropValue.ToString() != oldPropValue.ToString())
{
compareResult = false;
compareMsg += keyValueByFields[item.Name] + "【" + oldPropValue + "】修改为【" + newPropValue + "】<br>";
}
}
}
}
}
}

return new Tuple<bool, string>(compareResult, compareMsg);
}

原文地址:https://www.cnblogs.com/morpheusliu/p/15174587.html