using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using AutoMapper; namespace MyCode.Project.Infrastructure.Common { public class AutoMapperHelper { /// /// 映射单个实体 /// /// 目标对象 /// 数据来源对象 /// 数据原变量 /// public static T AutoMappToSingle(F fromData) { var datatype = fromData.GetType(); Mapper.Initialize(x => { x.CreateMap (); }); var result = Mapper.Map(fromData); return result; } /// /// 映射LIST /// /// 目标对象List /// 数据来源对象List /// 数据原变量List /// public static List AutoMappToList(List fromData) { var datatype = fromData.GetType(); Mapper.Initialize(x => { x.CreateMap(); }); var result = Mapper.Map>(fromData); return result; } /// /// 将返回的实体中的指定类型的NULL值转为 指定的值 /// /// 要修改的实体的类型 /// 要指定的值的类型 /// 要修改的实体 /// 要指定的值 public static void ClearNullOfEntity(T ToEntity, H NewValue) where T : new() { if (ToEntity != null) { PropertyInfo[] proFEntity = ToEntity.GetType().GetProperties(); foreach (PropertyInfo pi in proFEntity) { string NewValueTypeName = NewValue.GetType().Name; string PiTypeName = pi.PropertyType.Name; var item = pi.PropertyType.GenericTypeArguments.FirstOrDefault(); if (NewValue.GetType().Name.Equals(pi.PropertyType.Name) || (item != null && item.Name == NewValueTypeName)) { var value = pi.GetValue(ToEntity); if (value == null) { try { pi.SetValue(ToEntity, NewValue, null); } catch { } } } } } } } }