333
This commit is contained in:
90
MyCode.Project.Infrastructure/Common/AutoMapperHelper.cs
Normal file
90
MyCode.Project.Infrastructure/Common/AutoMapperHelper.cs
Normal file
@@ -0,0 +1,90 @@
|
||||
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
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user