You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
79 lines
2.5 KiB
79 lines
2.5 KiB
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<T>(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<T>(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<T>(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<PropertyInfo, bool> 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);
|
|
}
|
|
}
|
|
} |