using System; using System.Collections.Generic; using System.Linq; namespace CZFW.Core.Mapper { public class CZMapper { public static (TTarget target, bool hasError) Map(TSource source) { var sourceType = typeof(TSource); var sourceProperties = sourceType.GetProperties(); var targetType = typeof(TTarget); var targetProperties = targetType.GetProperties(); var res = Activator.CreateInstance(); var hasError = false; foreach (var item in targetProperties) { foreach (var sitem in sourceProperties) { if (item.Name == sitem.Name && item.PropertyType == sitem.PropertyType) { try { item.SetValue(res, sitem.GetValue(source)); } catch (Exception err) { hasError = true; } } } } return (res, hasError); } public static (IList targets, bool hasError) Map(IList source) { var res = new List<(TTarget, bool)>(); foreach (var item in source) { var tp = Map(item); res.Add(tp); } var hasError = res.Count(x => x.Item2) > 0; return (res.Select(x => x.Item1).ToList(), hasError); } public static (TEntity result, bool hasError) UpdateEntity(TEntity fromObj, TEntity toObj, bool updateDefaultValue = false) { var properties = typeof(TEntity).GetProperties(); foreach (var p in properties) { var fromValue = p.GetValue(fromObj); var toValue = p.GetValue(toObj); if (fromValue != toValue) { if (!updateDefaultValue) { var defVal = DefaultForType(p.PropertyType); if (fromValue != defVal) { p.SetValue(toObj, fromValue); } } else { p.SetValue(toObj, fromValue); } } } return (toObj, false); } static TType GetDefault() { return default(TType); } public static object DefaultForType(Type targetType) { return targetType.IsValueType ? Activator.CreateInstance(targetType) : null; } } }