AutoMapperHelper

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

nuget安装:

AutoMapperHelper_第1张图片

AutoMapperHelper代码:

/// 
    /// AutoMapper帮助类
    /// 
    public static class AutoMapperHelper
    {
        /// 
        ///  单个对象映射
        /// 
        public static T MapTo(this object obj)
        {
            if (obj == null) return default(T);
            Mapper.Reset();
            Mapper.Initialize(x => x.CreateMap(obj.GetType(), typeof(T)));
            return Mapper.Map(obj);
        }

        /// 
        /// 集合列表类型映射
        /// 
        public static List MapToList(this IEnumerable source)
        {
            if (source == null) return null;
            Mapper.Reset();
            Mapper.Initialize(x => x.CreateMap());
            return Mapper.Map>(source);
        }
    }

调用代码:

/// 
        /// 赋值
        /// 
        /// 
        /// 
        [HttpPost]
        public StudentEntity MapToStudent(AddStudentRequest request)
        {
            return request.MapTo();
        }

public class AddStudentRequest
    {
        /// 
        /// 姓名
        /// 
        public string StuName { get; set; } = string.Empty;

        /// 
        /// 年龄
        /// 
        public int Age { get; set; } = 0;
    }

/// 
    /// 学生
    /// 
    public class StudentEntity
    {
        /// 
        /// 学号
        /// 
        public int StuId { get; set; } = 0;

        /// 
        /// 姓名
        /// 
        public string StuName { get; set; } = string.Empty;

        /// 
        /// 年龄
        /// 
        public int Age { get; set; } = 0;
    }

 

你可能感兴趣的:(工具类)