AutoMapperHelper

主要场景、实体/集合映射赋值

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;
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值