AutoMapper简单用法

首先在NuGet添加AutoMapper

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

        /// <summary>
        /// 集合列表类型映射
        /// </summary>
        public static List<TDestination> MapToList<TSource, TDestination>(this IEnumerable<TSource> source)
        {
            Mapper.Initialize(x => Mapper.CreateMap<TSource, TDestination>());
            return Mapper.Map<List<TDestination>>(source);
        }
    }

  字段对应问题

 Mapper.Initialize(x => Mapper.CreateMap<Temp, TempVo>()
                .ForMember(dest => dest.age1,
                    opts => opts.MapFrom(src => src.age)));

var testVo1 = Mapper.Map<Temp, TempVo>(test);

  

posted @ 2016-12-14 14:57  mysuper  阅读(994)  评论(0编辑  收藏  举报