• AutoMapper项目实践



    本次示例,我们单独创建一个 AutoMapperService 的项目,用于放置映射配置文件,映射注册方法,映射公共方法。

    1.映射配置文件

    用于配置源实体到目标实体的映射

    public class AccountProfile : AutoMapper.Profile
    {
        public AccountProfile()
        {
    		//配置源实体AccountEntity到目标实体AccountViewModel的映射
            CreateMap<AccountEntity, AccountViewModel>();            
        }
    }
    

    在项目中根据实际需求,按照业务创建不同的配置文件,比如用户配置文件UserProfile,配置用户相关实体的映射;订单配置文件OrderProfile配置订单业务相关实体的映射。

    2.映射注册方法

    public class MappingConfig
    {
        //public static void Init()
        //{
        //    AutoMapper.Mapper.Initialize(cfg => {
        //        cfg.AddProfile<Profiles.AccountProfile>();
        //    });
        //}
    	
        private static readonly Type BaseType = typeof(AutoMapper.Profile);
        public static void RegisterMaps()
        {  
            //加载 AutoMapperService的程序集
            var assembly = System.Reflection.Assembly.Load("AutoMapperService");
            //筛选出继承AutoMapper.Profile的映射配置文件,所有映射配置文件都必须继承AutoMapper.Profile
            var types = assembly.GetTypes().Where(t => t.BaseType.Equals(BaseType));
            //初始化映射配置文件
            AutoMapper.Mapper.Initialize(cfg => {
                cfg.AddProfiles(types);
            });
        }
    }
    

    本示例采用加载程序集统一注册方法,项目后期需要添加新的映射配置文件,直接添加即可

    3.映射公共方法

    3.1方法介绍

    该方法包含常用的实体映射,List映射,IEnumerable映射等

    public static class AutoMapperHelper
    {
        /// <summary>   
        /// 集合对集合     
        /// </summary>   
        /// <typeparam name="TResult"></typeparam>   
        /// <param name="self"></param>   
        /// <returns></returns>   
        public static IEnumerable<TResult> MapTo<TResult>(this System.Collections.IEnumerable self)
        {
            if (self == null) throw new ArgumentNullException();
            return (IEnumerable<TResult>)Mapper.Map(self, self.GetType(), typeof(IEnumerable<TResult>));
        }
    
        /// <summary>   
        /// 集合对集合     
        /// </summary>   
        /// <typeparam name="TResult"></typeparam>   
        /// <param name="self"></param>   
        /// <returns></returns>   
        public static List<TResult> MapTo<TSource, TResult>(this List<TSource> self)
        {
            if (self == null) throw new ArgumentNullException();
            return Mapper.Map<List<TSource>, List<TResult>>(self);           
        }
        /// <summary>   
        /// 对象对对象   
        /// </summary>   
        /// <typeparam name="TResult"></typeparam>   
        /// <param name="self"></param>   
        /// <returns></returns>  
        public static TResult MapTo<TResult>(this object self)
        {
            if (self == null) throw new ArgumentNullException();            
            return (TResult)Mapper.Map(self, self.GetType(), typeof(TResult));
        }
    }
    

    3.2项目中如何使用

    //添加AutoMapperService引用
    using AutoMapperService;
    public class AccountLogic
    {
        private readonly AccountService _accountSer;
        public AccountLogic(AccountService accountSer)
        {
            this._accountSer = accountSer;
        }
        public AccountViewModel GetAccountById(int id)
        {			
            //目标实体
            AccountViewModel res = null;	        
            //源实体
            AccountEntity sourceEntity = _accountSer.GetAccount(id);	        
            //调用MapTo方法向目标实体映射
    		//AccountEntity到AccountViewModel的映射,已在AccountProfile文件中配置
            if (entity != null)
            {
                res = sourceEntity.MapTo<AccountViewModel>();            
            }
            return res;
        }
    }
    

    4.Web项目如何调用AutoMapper注册方法

    本次示例,是在.Net Framework4.6.1框架下MVC模式开发,在web层中Global.asax文件下,在Application_Start方法调用AutoMapper注册方法即可

    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            WebApiConfig.Register(System.Web.Http.GlobalConfiguration.Configuration);
            Filters.FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
    		//调用AutoMapper注册方法
            MappingConfig.RegisterMaps();
        }
    }
    

    4.单元测试项目如何调用AutoMapper注册方法

    在单元测试项目添加TestStart文件,如下内容,单元测试每次启动之前会自动调用Start方法,对AutoMapper的配置文件进行注册。若没有注册,在单元测试中调用3.2中的GetAccountById方法时,对象映射会失败。

    /// <summary>
    /// 单元测试启动之前初始化
    /// </summary>
    [TestClass]
    public class TestStart
    {
        /// <summary>
        /// 初始化逻辑方法
        /// </summary>
        [AssemblyInitialize]
        public static void Start(TestContext context = null)
        {
            //调用AutoMapper的注册            
            AutoMapperService.MappingConfig.RegisterMaps();
        }
    }
  • 相关阅读:
    项目测试与部署
    使用技术及部分代码截选
    校园电子设备报修回收系统需求分析
    java lambda expression
    Domain logic approaches
    Spring AOP Capabilities ang goals
    CDI Features
    JAVA DESIGN PATTERN
    LDAP & Implementation
    spring ref &history&design philosophy
  • 原文地址:https://www.cnblogs.com/wuyunblog/p/9109957.html
Copyright © 2020-2023  润新知