/// <summary> /// 为Entity赋值 /// </summary> /// <typeparam name="T">Entity</typeparam> /// <param name="t">Entity</param> /// <param name="form">Request</param> /// <param name="prefix">前缀</param> public static void UpdateModel <T>(T t, NameValueCollection form, string prefix) where T : Entity { Field[] fields = EntityCache.GetFields <T>(); string temp = prefix ?? string.Empty; foreach (Field f in fields) { string tempValue = form[temp + f.PropertyName]; if (null != tempValue) { string propertyName = f.PropertyName; PropertyInfo property = t.GetType().GetProperty(propertyName); if (null == property) { propertyName = string.Concat(propertyName.Substring(0, 1).ToUpper(), propertyName.Substring(1)); property = t.GetType().GetProperty(propertyName); } if (null != property) { DataUtils.SetPropertyValue(t, property, tempValue); } } } }
/// <summary> /// 为Entity赋值 /// </summary> /// <typeparam name="T">Entity</typeparam> /// <param name="t">Entity</param> /// <param name="form">Request</param> /// <param name="prefix">前缀</param> /// <returns>转换是否成功</returns> public static bool TryUpdateModel <T>(T t, NameValueCollection form, string prefix) { bool success = true; Field[] fields = EntityCache.GetFields <T>(); string temp = prefix ?? string.Empty; foreach (Field f in fields) { string tempValue = form[temp + f.PropertyName]; if (null != tempValue) { try { string propertyName = f.PropertyName; PropertyInfo property = t.GetType().GetProperty(propertyName); if (null == property) { propertyName = string.Concat(propertyName.Substring(0, 1).ToUpper(), propertyName.Substring(1)); property = t.GetType().GetProperty(propertyName); } if (null != property) { DataUtils.SetPropertyValue(t, property, tempValue); } } catch { success = false; } } } return(success); }
/// <summary> /// 实体赋值 /// </summary> /// <typeparam name="TEntity"></typeparam> /// <param name="toEntity">被赋值实体</param> /// <param name="fromEntity">来源实体</param> /// <returns>返回null 就表示fromEntity==null</returns> public static void SetValue <TEntity>(TEntity toEntity, TEntity fromEntity) where TEntity : Entity { if (null == fromEntity) { toEntity = null; } else { if (null == toEntity) { toEntity = DataUtils.Create <TEntity>(); } toEntity.Attach(); PropertyInfo[] pis = toEntity.GetType().GetProperties(); foreach (PropertyInfo pi in pis) { DataUtils.SetPropertyValue(toEntity, pi, DataUtils.GetPropertyValue <TEntity>(fromEntity, pi.Name)); } } }