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.

64 lines
2.1 KiB
C#

1 year ago
using AutoMapper;
namespace DS.Module.Core.Extensions;
/// <summary>
/// AutoMapper扩展类
/// </summary>
public static class AutoMapperExtension
{
/// <summary>
/// 对象映射
/// </summary>
public static TOut MapTo<TIn, TOut>(this TIn source)
{
if (source == null) return default(TOut);
var config = new MapperConfiguration(cfg => cfg.CreateMap<TIn, TOut>());
var mapper = config.CreateMapper();
return mapper.Map<TOut>(source);
}
/// <summary>
/// 对象映射(自定义)
/// </summary>
public static TOut MapTo<TIn, TOut>(this TIn source, Profile profile)
{
if (source == null) return default(TOut);
var config = new MapperConfiguration(cfg => cfg.AddProfile(profile));
var mapper = config.CreateMapper();
return mapper.Map<TOut>(source);
}
/// <summary>
/// 集合映射
/// </summary>
/// <typeparam name="TSource"></typeparam>
/// <typeparam name="TDestination"></typeparam>
/// <param name="source"></param>
/// <returns></returns>
public static IEnumerable<TDestination> MapToList<TSource, TDestination>(this IEnumerable<TSource> source)
{
if (source == null) return new List<TDestination>();
var config = new MapperConfiguration(cfg => cfg.CreateMap<TSource, TDestination>());
var mapper = config.CreateMapper();
return mapper.Map<List<TDestination>>(source);
}
/// <summary>
/// 集合映射(自定义)
/// </summary>
/// <typeparam name="TSource"></typeparam>
/// <typeparam name="TDestination"></typeparam>
/// <param name="source"></param>
/// <param name="profile"></param>
/// <returns></returns>
public static IEnumerable<TDestination> MapToList<TSource, TDestination>(this IEnumerable<TSource> source,
Profile profile)
{
if (source == null) return new List<TDestination>();
var config = new MapperConfiguration(cfg => cfg.AddProfile(profile));
var mapper = config.CreateMapper();
return mapper.Map<List<TDestination>>(source);
}
}