#region Model字段修改记录
/// <summary>
/// 获取Entity 修改的字段值
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="newEntity"></param>
/// <param name="oldEntity"></param>
/// <param name="ignoreColumnList">忽略的列名列表</param>
/// <returns></returns>
public static List<ValueModifiedModel> GetModifiedModels<T>( T newEntity, T oldEntity, List<string> ignoreColumnList) where T : class
{
List<ValueModifiedModel> valueModifiedList = new List<ValueModifiedModel>();
Type entityType = typeof(T);
PropertyInfo[] properties = entityType.GetProperties().Where(o => o.CanWrite && PrimitiveTypes.Contains(o.PropertyType) && !o.GetCustomAttributes(false).OfType<NotMappedAttribute>().Any()).ToArray();
foreach (var p in properties)
{
if (ignoreColumnList.Contains(p.Name))
continue;
object oldValue = p.GetValue(oldEntity, null);
object newValue = p.GetValue(newEntity, null);
if ((oldValue == null && newValue == null))
{
continue;
}
else if (oldValue == null && newValue != null || oldValue != null && newValue == null || !TypeConvert(p.PropertyType, oldValue, newValue))
{
valueModifiedList.Add(new ValueModifiedModel()
{
ColumnName = p.Name,
OldValue = oldValue ?? "NULL",
NewValue = newValue ?? "NULL"
}
);
}
}
return valueModifiedList;
}
/// <summary>
/// 字段类型
/// </summary>
public static HashSet<Type> PrimitiveTypes = new HashSet<Type>()
{
typeof(String),
typeof(Byte[]),
typeof(Byte),
typeof(Int16),
typeof(Int32),
typeof(Int64),
typeof(Single),
typeof(Double),
typeof(Decimal),
typeof(DateTime),
typeof(Guid),
typeof(Boolean),
typeof(TimeSpan),
typeof(Byte?),
typeof(Int16?),
typeof(Int32?),
typeof(Int64?),
typeof(Single?),
typeof(Double?),
typeof(Decimal?),
typeof(DateTime?),
typeof(Guid?),
typeof(Boolean?),
typeof(TimeSpan?)
};
/// <summary>
/// 数据类型转换
/// </summary>
/// <param name="propertyType"></param>
/// <param name="oldValue"></param>
/// <param name="newValue"></param>
/// <returns></returns>
private static bool TypeConvert(Type propertyType, object oldValue, object newValue)
{
if (propertyType == typeof(Decimal) || propertyType == typeof(Decimal?))
{
return decimal.Parse(oldValue.ToString()) == decimal.Parse(newValue.ToString());
}
else
{
return string.Equals(oldValue.ToString(), newValue.ToString());
}
}
/// <summary>
/// 修改字段实体类
/// </summary>
public class ValueModifiedModel
{
/// <summary>
/// 字段名称
/// </summary>
public string ColumnName { get; set; }
/// <summary>
/// 旧值
/// </summary>
public object OldValue { get; set; }
/// <summary>
/// 新值
/// </summary>
public object NewValue { get; set; }
}
#endregion