2025-04-24 18:31:27 +08:00

91 lines
2.9 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using AutoMapper;
namespace MyCode.Project.Infrastructure.Common
{
public class AutoMapperHelper
{
/// <summary>
/// 映射单个实体
/// </summary>
/// <typeparam name="T">目标对象</typeparam>
/// <typeparam name="F">数据来源对象</typeparam>
/// <param name="fromData">数据原变量</param>
/// <returns></returns>
public static T AutoMappToSingle<T,F>(F fromData)
{
var datatype = fromData.GetType();
Mapper.Initialize(x => {
x.CreateMap<F,T> ();
});
var result = Mapper.Map<T>(fromData);
return result;
}
/// <summary>
/// 映射LIST
/// </summary>
/// <typeparam name="T">目标对象List</typeparam>
/// <typeparam name="F">数据来源对象List</typeparam>
/// <param name="fromData">数据原变量List</param>
/// <returns></returns>
public static List<T> AutoMappToList<T, F>(List<F> fromData)
{
var datatype = fromData.GetType();
Mapper.Initialize(x => {
x.CreateMap<F, T>();
});
var result = Mapper.Map<List<T>>(fromData);
return result;
}
/// <summary>
/// 将返回的实体中的指定类型的NULL值转为 指定的值
/// </summary>
/// <typeparam name="T">要修改的实体的类型</typeparam>
/// <typeparam name="H">要指定的值的类型</typeparam>
/// <param name="ToEntity">要修改的实体</param>
/// <param name="NewValue">要指定的值</param>
public static void ClearNullOfEntity<T, H>(T ToEntity, H NewValue) where T : new()
{
if (ToEntity != null)
{
PropertyInfo[] proFEntity = ToEntity.GetType().GetProperties();
foreach (PropertyInfo pi in proFEntity)
{
string NewValueTypeName = NewValue.GetType().Name;
string PiTypeName = pi.PropertyType.Name;
var item = pi.PropertyType.GenericTypeArguments.FirstOrDefault();
if (NewValue.GetType().Name.Equals(pi.PropertyType.Name) || (item != null && item.Name == NewValueTypeName))
{
var value = pi.GetValue(ToEntity);
if (value == null)
{
try
{
pi.SetValue(ToEntity, NewValue, null);
}
catch
{
}
}
}
}
}
}
}
}