AutoMapper的使用

在使用DTO概念后,使用AutoMapper进行对象的映射,使用4.0.4版本的AutoMapper.

AutoMapper的辅助类:

/// <summary>   
    /// AutoMapper扩展方法   
    /// </summary>   
    public static class AutoMapperExtension
    {
        /// <summary>
        ///  类型映射
        /// </summary>
        public static T MapTo<T>(this object obj)
        {
            if (obj == null) return default(T);
            Mapper.CreateMap(obj.GetType(), typeof(T));
            return Mapper.Map<T>(obj);
        }
        /// <summary>
        /// 集合列表类型映射
        /// </summary>
        public static List<TDestination> MapToList<TDestination>(this IEnumerable source)
        {
            foreach (var first in source)
            {
                var type = first.GetType();
                Mapper.CreateMap(type, typeof(TDestination));
                break;
            }
            return Mapper.Map<List<TDestination>>(source);
        }
        /// <summary>
        /// 集合列表类型映射
        /// </summary>
        public static List<TDestination> MapToList<TSource, TDestination>(this IEnumerable<TSource> source)
        {
            //IEnumerable<T> 类型需要创建元素的映射
            Mapper.CreateMap<TSource, TDestination>();
            return Mapper.Map<List<TDestination>>(source);
        }
    }

有特殊字段需要进行处理的,可以使用ForMember

 #region Mapper映射
            Mapper.CreateMap<WareHouse_Achievement, AchievementOutputDto>().ForMember(c => c.TargetCompleteness, opt =>
              {
                  opt.MapFrom(s => s.AchievementTarget > 0 ? Math.Round((s.TotalAchiToday / s.AchievementTarget * 100), 2).ToString() + "%" : "");
              }).ForMember(c => c.PointCompleteness, opt =>
                {
                    opt.MapFrom(s => s.BreakEvenPoint > 0 ? Math.Round((s.TotalAchiToday / s.BreakEvenPoint * 100), 2).ToString() + "%" : "");
                });
            var outs = Mapper.Map<List<AchievementOutputDto>>(list);
            var outList = AutoMapperExtension.MapToList<AchievementOutputDto>(list);

 

posted on 2016-12-13 14:58  勤劳的Coder  阅读(580)  评论(0编辑  收藏  举报