You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

67 lines
2.2 KiB
C#

using AutoMapper;
namespace DS.Module.AutoMapper;
/// <summary>
/// AutoMapper扩展类
/// </summary>
public static class AutoMapperExtension1
{
/// <summary>
/// 将源对象映射到目标对象
/// </summary>
/// <typeparam name="T">实体类型</typeparam>
/// <param name="obj">源对象</param>
/// <returns>转化之后的实体</returns>
public static T MapTo<T>(this object obj)
{
if (obj == null) return default;
var config = new MapperConfiguration(ctx => ctx.CreateMap(obj.GetType(), typeof(T)));
var mapper = config.CreateMapper();
return mapper.Map<T>(obj);
}
/// <summary>
/// 映射
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dto"></param>
/// <param name="entity"></param>
/// <returns></returns>
public static T Map<T>(object dto, T entity)
{
var config = new MapperConfiguration(ctx => ctx.CreateMap(dto.GetType(), typeof(T)));
var mapper = config.CreateMapper();
var newModel = mapper.Map(dto, entity);
return newModel;
}
/// <summary>
/// 单个实体映射
/// </summary>
/// <typeparam name="TSource">源对象类型</typeparam>
/// <typeparam name="TDestination">目标对象类型</typeparam>
/// <param name="source"></param>
/// <returns></returns>
public static TDestination MapTo<TSource, TDestination>(this TSource source)
{
if (source == null) return default;
var config = new MapperConfiguration(ctx => ctx.CreateMap<TSource, TDestination>());
var mapper = config.CreateMapper();
return mapper.Map<TDestination>(source);
}
/// <summary>
/// 集合映射
/// </summary>
/// <typeparam name="TSource">源对象类型</typeparam>
/// <typeparam name="TDestination">目标对象类型</typeparam>
/// <param name="source"></param>
/// <returns></returns>
public static IEnumerable<TDestination> MapTo<TSource, TDestination>(this IList<TSource> source)
{
var config = new MapperConfiguration(cfg => cfg.CreateMap<TSource, TDestination>());
var mapper = config.CreateMapper();
return mapper.Map<IList<TDestination>>(source);
}
}