/// <summary> ///创建人:蒋云峰 ///日 期:2019/12/23 ///描 述:更新实体,与数据库实体进行对比 /// </summary> public class JyfUpdateModel { /// <summary> /// 当dataBaseObj与newObj具有相同的属性名时,如果newObj的这个属性没有值,则把dataBaseObj中的属性值赋值为newObj的这个属性 /// 主要用于更新,防止清空掉原有的数据 /// </summary> /// <param name="dataBaseObj">EF查询数据库得到的Model</param> /// <param name="newObj">表单提交到Action时,框架自动根据表单里面的字段创建的Model</param> public static void updateModel(object dataBaseObj, object newObj) { Type t = dataBaseObj.GetType(); //3.2.3?获取实体类所有的公共属性?? List<PropertyInfo> propertyInfos = t.GetProperties(BindingFlags.Instance | BindingFlags.Public).ToList(); //3.2.4?创建实体属性字典集合?? Dictionary<string, PropertyInfo> dicPropertys = new Dictionary<string, PropertyInfo>(); //3.2.5?将实体属性中要修改的属性名?添加到字典集合中??键:属性名??值:属性对象?? propertyInfos.ForEach(p => { dicPropertys.Add(p.Name, p); }); Type t2 = newObj.GetType(); foreach (var item in t2.GetProperties(BindingFlags.Instance | BindingFlags.Public).ToList()) { if (dicPropertys.Keys.Contains(item.Name)) { try { if (item.GetValue(newObj) == null && dicPropertys[item.Name].GetValue(dataBaseObj) != null) { item.SetValue(newObj, dicPropertys[item.Name].GetValue(dataBaseObj)); } } catch (Exception ex) { throw; } } } } }
原文地址:https://www.cnblogs.com/jiangyunfeng/p/12607863.html
时间: 2024-10-01 07:26:03