using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; namespace Common.Helper.Entity { public class ModelToEntity { /// /// 类型转换,有则赋值,没有则默认值 这个可以不传需要转换的值 /// /// /// public static TE Change(TM model) { var modelPropertyInfos = typeof(TM).GetProperties(); var entityType = typeof(TE); var entity =(TE)Activator.CreateInstance(typeof(TE)); foreach (var modelPropertyInfo in modelPropertyInfos) { if(entityType.GetProperty(modelPropertyInfo.Name)!=null) entityType.GetProperty(modelPropertyInfo.Name)?.SetValue(entity, modelPropertyInfo.GetValue(model), null); } return entity; } /// /// 类型转换,只是这个可以传入需要转换的值 /// /// /// /// public static TE Set(TM model,TE entity) { var modelPropertyInfos = typeof(TM).GetProperties(); var entityType = typeof(TE); foreach (var modelPropertyInfo in modelPropertyInfos) { if (entityType.GetProperty(modelPropertyInfo.Name) != null) entityType.GetProperty(modelPropertyInfo.Name)?.SetValue(entity, modelPropertyInfo.GetValue(model), null); } return entity; } } }