using ModelTools.Attributes;
using System;
using System.Reflection;
namespace ModelTools.BusinessLogics
{
///
/// Маппер сущностей
///
public class Mapper
{
///
/// Преобразование из одного класса в другой
///
///
///
///
///
public static To MapToClass(From obj) where To : class => FillObject(obj, (To)Activator.CreateInstance(typeof(To)));
///
/// Преобразование из одного класса в другой
///
///
///
///
///
///
public static To MapToClass(From obj, To newObject) where To : class => FillObject(obj, newObject);
///
/// Заполнение объекта
///
///
///
///
///
///
private static To FillObject(From obj, To newObject)
where To : class
{
if (obj == null)
{
return null;
}
if (newObject == null)
{
return null;
}
var typeFrom = typeof(From);
var typeTo = typeof(To);
var properties = typeTo.GetProperties();
foreach (var property in properties)
{
var customAttribute = property.GetCustomAttribute();
if (customAttribute != null)
{
object value = obj;
if (customAttribute.IsDifficle)
{
var props = customAttribute.PropertyNameFromModel.Split('.');
foreach (var prop in props)
{
var bindingProperty = value.GetType().GetProperty(prop);
if (bindingProperty != null)
{
value = bindingProperty.GetValue(value);
if (value is null)
{
break;
}
}
else
{
value = null;
break;
}
}
}
else
{
var bindingProperty = typeFrom.GetProperty(customAttribute.PropertyNameFromModel);
if (bindingProperty != null)
{
value = bindingProperty.GetValue(obj);
}
}
if (value is null)
{
continue;
}
property.SetValue(newObject, value);
}
}
return newObject;
}
}
}