首页 > 代码库 > 对比Model前后数据保存不同值

对比Model前后数据保存不同值

1.示例代码
public class SysLogBLL<T,W> : BLLBase where T : new() { #region 比较方法 /// <summary> /// 复制对象到指定对象中 只复制名称一样的 /// </summary> /// <param name="obj"></param> /// <returns></returns> public T Clone(W obj) { Type objTye = typeof(T); Type objTyeW = typeof(W); T t = new T(); PropertyInfo[] proinfos = objTye.GetProperties(); PropertyInfo[] proinfosw = objTyeW.GetProperties(); foreach (var i in proinfos) { foreach (var j in proinfosw) { if (i.Name == j.Name) { object o = j.GetValue(obj, null); if (i.GetSetMethod() != null) { i.SetValue(t, o, null); } } } } return t; } public T Clone(T obj) { Type objTye = typeof(T); T model = new T(); PropertyInfo[] properties = objTye.GetProperties(); foreach (PropertyInfo property in properties) { if (!property.IsSpecialName) { object o = property.GetValue(obj, null); if (property.GetSetMethod() != null) { property.SetValue(model, o, null); } } } return model; } private bool IsEqual(Type dataType, object oldObj, object newObj) { if (oldObj == null && newObj == null) return true; if (oldObj != null && newObj != null) { if (dataType == typeof(int)) return (int)oldObj == (int)newObj; if (dataType == typeof(decimal)) return (decimal)oldObj == (decimal)newObj; if (dataType == typeof(double)) return (double)oldObj == (double)newObj; if (dataType == typeof(Guid)) return (Guid)oldObj == (Guid)newObj; if (dataType == typeof(DateTime)) return (DateTime)oldObj == (DateTime)newObj; if (dataType == typeof(string)) return (string)oldObj == (string)newObj; return true; //return oldObj.Equals(newObj); } else { if (dataType.BaseType == typeof(object)) return true; else return false; } } /// <summary> /// 比较两个实体,然后返回实体中每个属性值不同的内容 /// </summary> /// <param name="oldObj"></param> /// <param name="newObj"></param> /// <returns></returns> public List<Hashtable> Compare(T oldObj, T newObj) { Type objTye = typeof(T); List<Hashtable> list = new List<Hashtable>(); // FieldInfo[] myFields = objTye.GetFields(BindingFlags.Public | BindingFlags.Instance); PropertyInfo[] proinfos = objTye.GetProperties(); try { foreach (var item in proinfos) { object o = item.GetValue(oldObj, null); object n = item.GetValue(newObj, null); var itype = item.PropertyType.GetGenericArguments(); Type itemtype = itype.Length > 0 ? itype[0] : item.PropertyType; if (!IsEqual(itemtype, o, n)) { Hashtable hs = new Hashtable(); hs.Add("Key", item.Name); hs.Add("KeyType", (itemtype != null ? itemtype.Name : item.PropertyType.Name)); hs.Add("oValue", o); hs.Add("nValue", n); list.Add(hs); } } } catch (Exception ex) { throw; } return list; } #endregion #region 保存LogAction /// <summary> /// 保存数据 /// </summary> /// <param name="Lgaction">Crm_LogAction 对象</param> /// <param name="originaldata">原始对象数据</param> /// <param name="currentdata">当前对象数据</param> /// <returns></returns> public bool SaveLogActoin(Crm_LogAction Lgaction, T originaldata, T currentdata) { bool result = false; //执行结果 if (Lgaction != null) { try { MainEntities.Crm_LogAction.Add(Lgaction); MainEntities.SaveChanges();
List
<Hashtable> lt = Compare(originaldatacurrentdata);
if (lt.Count() > 0)                    {                        foreach (var h in lt)                        {                            Hashtable hitem = h as Hashtable;                            if (hitem != null && hitem.Count > 0)                            {                                MainEntities.Crm_LogActionDetail.Add(new Crm_LogActionDetail                                {                                    LogId = Lgaction.LogId,                                    ColumnName = hitem["Key"].ToString(),                                    ColumnDataType = hitem["KeyType"].ToString(),                                    CreateTime = DateTime.Now,                                    CreateUser = CurrentUser.Name + "[" + CurrentUser.Id + "]",                                    NewValue = hitem["nValue"].ToString(),                                    OldValue = hitem["oValue"].ToString(),                                });                            }                        }                        MainEntities.SaveChanges();                        result = true;                    }                }                catch (Exception)                {                    result = false;                }            }            return result;        }        /// <summary>        ///  保存数据         /// </summary>        /// <param name="TableName">表名</param>        /// <param name="OperationId">操作类型 0=add  1=delte  2=update </param>        /// <param name="originaldata"></param>        /// <param name="currentdata"></param>        /// <returns></returns>        public bool SaveLogActoin(string TableName, int OperationId, T originaldata, T currentdata)        {            bool result = false; //执行结果                         Crm_LogAction Lgaction=new Crm_LogAction ();                try                {                    var query = MainEntities.Crm_LogActionType.Where(w => w.TableName == TableName).SingleOrDefault();                     if (query != null)                     {                         Lgaction=   new Crm_LogAction                            {                                OperationId = OperationId,//修改=2                                CreateTime = DateTime.Now,                                CreateUser = CurrentUser.Name + "[" + CurrentUser.Id + "]",                                LogTypeId = query.TypeId,                                TableName = query.TableName,                                BusinessName = query.BusinessName                            };                       MainEntities.Crm_LogAction.Add(Lgaction);                       MainEntities.SaveChanges();                      List<Hashtable> lt = Compare(originaldata, currentdata);if (lt.Count() > 0)                       {                           foreach (var h in lt)                           {                               Hashtable hitem = h as Hashtable;                               if (hitem != null && hitem.Count > 0)                               {                                   MainEntities.Crm_LogActionDetail.Add(new Crm_LogActionDetail                                   {                                       LogId = Lgaction.LogId,                                       ColumnName = hitem["Key"].ToString(),                                       ColumnDataType = hitem["KeyType"].ToString(),                                       CreateTime = DateTime.Now,                                       CreateUser = CurrentUser.Name + "[" + CurrentUser.Id + "]",                                       NewValue =hitem["nValue"]==null?"": hitem["nValue"].ToString(),                                       OldValue =hitem["oValue"]==null?"": hitem["oValue"].ToString(),                                   });                               }                           }                           MainEntities.SaveChanges();                           result = true;                       }                     }                                    }                catch (Exception)                {                    result = false;                }            return result;        }        #endregion    }

2.调用示例:

SysLogBLL<Crm_Contact, ContactBankCreateOrEdit> Syslog = new SysLogBLL<Crm_Contact, ContactBankCreateOrEdit>();
Crm_Contact currentdata = http://www.mamicode.com/Syslog.Clone(model); //新数据
Crm_Contact originaldata = http://www.mamicode.com/dModel;

Syslog.SaveLogActoin("Crm_Contact", 2, originaldata, currentdata);



 

对比Model前后数据保存不同值