主要场景、实体/集合映射赋值
nuget安装:
AutoMapperHelper代码:
/// <summary>
/// AutoMapper帮助类
/// </summary>
public static class AutoMapperHelper
{
/// <summary>
/// 单个对象映射
/// </summary>
public static T MapTo<T>(this object obj)
{
if (obj == null) return default(T);
Mapper.Reset();
Mapper.Initialize(x => x.CreateMap(obj.GetType(), typeof(T)));
return Mapper.Map<T>(obj);
}
/// <summary>
/// 集合列表类型映射
/// </summary>
public static List<TDestination> MapToList<TSource, TDestination>(this IEnumerable<TSource> source)
{
if (source == null) return null;
Mapper.Reset();
Mapper.Initialize(x => x.CreateMap<TSource, TDestination>());
return Mapper.Map<List<TDestination>>(source);
}
}
调用代码:
/// <summary>
/// 赋值
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
[HttpPost]
public StudentEntity MapToStudent(AddStudentRequest request)
{
return request.MapTo<StudentEntity>();
}
public class AddStudentRequest
{
/// <summary>
/// 姓名
/// </summary>
public string StuName { get; set; } = string.Empty;
/// <summary>
/// 年龄
/// </summary>
public int Age { get; set; } = 0;
}
/// <summary>
/// 学生
/// </summary>
public class StudentEntity
{
/// <summary>
/// 学号
/// </summary>
public int StuId { get; set; } = 0;
/// <summary>
/// 姓名
/// </summary>
public string StuName { get; set; } = string.Empty;
/// <summary>
/// 年龄
/// </summary>
public int Age { get; set; } = 0;
}