using Common.Models; using Newtonsoft.Json; using System; using System.Reflection; namespace Common { public static class ToModeExtension { public static T ToModel(this T model, T data) where T : class, new() { if (model == null) return null; if (data == null) return model; PropertyInfo[] propertyInfos = data.GetType().GetProperties();//获取实体下所有字段的属性 PropertyInfo[] dtoproperty = model.GetType().GetProperties(); for (int i = 0; i < propertyInfos.Length; i++) { for (int j = 0; j < dtoproperty.Length; j++) { if (propertyInfos[i].Name == dtoproperty[j].Name) { var ss = (TypeEnum)Enum.Parse(typeof(TypeEnum), propertyInfos[i].PropertyType.Name); var value = propertyInfos[i].GetValue(data);//获取该属性字段对应的值 if (value == null) break; switch (ss) { case TypeEnum.String: if(!string.IsNullOrEmpty(value.ToString())) dtoproperty[j].SetValue(model, value); break; case TypeEnum.Int32: if (propertyInfos[i].Name == "id") { if (Convert.ToInt32(value) > 0) dtoproperty[j].SetValue(model, value); } else { if (Convert.ToInt32(value) >= 0) dtoproperty[j].SetValue(model, value); } break; case TypeEnum.Boolean: if (Convert.ToBoolean(value) == true) dtoproperty[j].SetValue(model, value); break; case TypeEnum.DateTime: if (Convert.ToDateTime(value) > Convert.ToDateTime("1949/01/01 00:00:00")) dtoproperty[j].SetValue(model, value); break; case TypeEnum.Double: if (Convert.ToDouble(value) >= 0) dtoproperty[j].SetValue(model, value); break; case TypeEnum.Decimal: if (Convert.ToDecimal(value) >= 0) dtoproperty[j].SetValue(model, value); break; default: if (!string.IsNullOrEmpty(value.ToString())) dtoproperty[j].SetValue(model, value); break; } break; } } } return model; } public static T ToEntity(this object model) where T : class, new() { try { if (model == null) return null; T data = new T(); Type t = typeof(T); PropertyInfo[] propertyInfos = t.GetProperties();//获取实体下所有字段的属性 PropertyInfo[] dtoproperty = model.GetType().GetProperties(); for (int j = 0; j < dtoproperty.Length; j++) { for (int i = 0; i < propertyInfos.Length; i++) { if (propertyInfos[i].Name == dtoproperty[j].Name) { var value = dtoproperty[j].GetValue(model);//获取该属性字段对应的值 propertyInfos[i].SetValue(data, value); } } } return data; } catch (Exception e) { return null; } } #region object where public static string objectwhere(object parm) { string where = " n1>-1 "; if (parm != null) { foreach (PropertyInfo item in parm.GetType().GetProperties()) { where += $" and {item.Name}=@{item.Name} "; } if (!string.IsNullOrEmpty(where)) return " where " + where; } return " where " + where; } #endregion } }