mvc里的AutoMapper的帮助类

 using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Mvc;
using AutoMapper;
using AutoMapper.Attributes;

namespace FastToo.WebApp.HtmlHelper
{
    public static class AutoMapperHelper
    {
        static AutoMapperHelper()
        {
            Assembly.GetExecutingAssembly().GetTypes().Where(p => p.BaseType.Equals(typeof(Controller))).ToList()
                .ForEach(p =>
                {
                    AutoMapper.Mapper.Initialize(c => p.Assembly.MapTypes(c));
                });
        }
        /// 
        ///  类型映射
        /// 
        public static T MapTo(this object obj)
        {
            if (obj == null) return default(T);
            Mapper.Initialize(c => c.CreateMap(obj.GetType(), typeof(T)));
            return Mapper.Map(obj);
        }
        /// 
        /// 集合列表类型映射
        /// 
        public static List MapToList(this IEnumerable source)
        {
            foreach (var first in source)
            {
                var type = first.GetType();
                Mapper.Initialize(c => c.CreateMap(type, typeof(TDestination)));
                break;
            }
            return Mapper.Map>(source);
        }
        /// 
        /// 集合列表类型映射
        /// 
        public static List MapToList(this IEnumerable source)
        {
            //IEnumerable 类型需要创建元素的映射
            Mapper.Initialize(c => c.CreateMap());
            return Mapper.Map>(source);
        }
        /// 
        /// 类型映射
        /// 
        public static TDestination MapTo(this TSource source, TDestination destination)
            where TSource : class
            where TDestination : class
        {
            if (source == null) return destination;
            Mapper.Initialize(c => c.CreateMap());

            return Mapper.Map(source, destination);
        }
        /// 
        /// DataReader映射
        /// 
        public static IEnumerable DataReaderMapTo(this IDataReader reader)
        {
            Mapper.Reset();
            Mapper.Initialize(c => c.CreateMap());
            return Mapper.Map>(reader);
        }
    }
}

你可能感兴趣的:(.Net)