using Omu.ValueInjecter; using Omu.ValueInjecter.Injections; using System; using System.Linq; using System.Reflection; namespace Infrastructure.Extensions { public static class ObjectMapperExtensions { public static T From(this T target, object source, bool skipNull = false, string[] skips = null) { var injection = new NullableInjection(); injection.SkipNull = skipNull; injection.SkipProperties = skips; return (T)target.InjectFrom(injection, source); } public static T To(this object source, bool skipNull = false, string[] skips = null) { var injection = new NullableInjection(); injection.SkipNull = skipNull; injection.SkipProperties = skips; return (T)(Activator.CreateInstance(typeof(T)).InjectFrom(injection, source)); } // public static T FromDto(this T target, object source) { var injection = new NullableInjection(); injection.SkipFunc = o => o.Name.EndsWith("Id"); return (T)target.InjectFrom(injection, source); } } public class NullableInjection : LoopInjection { public bool SkipNull { get; set; } public string[] SkipProperties { get; set; } public Func SkipFunc { get; set; } protected override bool MatchTypes(Type sourceType, Type targetType) { var snt = Nullable.GetUnderlyingType(sourceType); var tnt = Nullable.GetUnderlyingType(targetType); return sourceType == targetType || sourceType == tnt || targetType == snt; } protected override void SetValue(object source, object target, PropertyInfo sp, PropertyInfo tp) { if (this.SkipNull) { var value = sp.GetValue(source); if (value == null) { return; } } if (this.SkipProperties != null && this.SkipProperties.Length > 0) { if (this.SkipProperties.Contains(sp.Name)) { return; } } if (this.SkipFunc != null) { if (this.SkipFunc(sp)) { return; } } base.SetValue(source, target, sp, tp); } } }