AutoMapper——最佳实践

通过配置文件控制要加载那些定义模型map的文件

指定map文件所在的程序集

然后通过Mapper的初始化方法添加

  
    
    
    
  

接下来定义一个加载这些程序集下面继承Profile的派生类的方法

    public static void LoadConfig(string sectionName = "autoMapper")
        {
            var config = ConfigurationManager.GetSection(sectionName).As();
            var assemlies = config.Keys
                .Cast()
                .Select(e => config[e])
                .Where(e => !e.IsNullOrEmpty())
                .ToArray();
            Mapper.Initialize(cfg => cfg.AddProfiles(assemlies));
            Mapper.AssertConfigurationIsValid();
        }

然后如果是MVC项目,在global.asax中的 Application_Start方法中调用上面的方法。

接下来只需要在需要模型map的地方预先创建模型之间的map关系

  /// AutoMapper映射配置
    public class AutoMapperProfile : Profile
    {
        /// 构造函数
        public AutoMapperProfile()
        {
            CreateMap()
                .ForMember(t => t.Enabled, opt => opt.Ignore())
                ;
        }
    }

在定义模型映射中的MapFrom 和ResolveUsing的区别

参数不同

MapFrom更适用于属性直接转化,会检查 是否为null

ResolveUsing 更适合复杂的属性转化,不会检查 是否为null

如果使用MapFrom在转化的过程中遇到抛出的null相关的异常,它会自动处理该异常,使之无法知道内部发生错误。

这是可以自定义resolver ,并使用ResolveUsing进行映射转化


下面来自参考:http://blog.travisgosselin.com/automapper-mapfrom-vs-resolveusing/


When specifying the mapping creation between two objects you have two possible approaches that are often used interchangeably by some without understanding the difference:


You can use the “ResolveUsing” method:
Mapper.CreateMap().ForMember(d => d.DestPropX, o => o.ResolveUsing(s => s.SourcePropY));


You can use the “MapFrom” method
Mapper.CreateMap().ForMember(d => d.DestPropX, o => o.MapFrom(s => s.SourcePropY));


In 90% of the time, these are going to and do the exact same thing, and you won’t have to worry. However, if you are doing a more complex flattening exercise for a property that won’t flatten by convention the “MapFrom” includes NULL checks all the way through the object graph. For example:


ForMember(d => d.DestPropX, o => o.MapFrom(s => s.Person.Address.State));


This scenario will not blow up your application if Person or Address is NULL, but instead NULL will be mapped over to the DestPropX safely. AutoMapper automatically catches the thrown NULL reference exception and hides it from you. That sounds AWESOME. But you need to be aware of the overhead price you pay in performance for using Exceptions during your normal workflow of your application.


Consider the scenario where I have a list of 1,000 objects to convert, all with a NULL Person property, in which cases we are looking at 1,000 Null reference exceptions that must be eatin’ inside your app. In my own experience, under the wrong scenario where this was multiplied many times, I had a single web service call that took about 10 sec. Upon investigating, I found that due to the number of exceptions thrown for NULL checks, my web service transformation was taking an extra 5 sec. I could easily get my 50% performance boost by doing some manual NULL checks with ResolveUsing:


ForMember(d => d.DestPropX, o => o.ResolveUsing(s => s.Person != null ? s.Person.Address.State : null ));


By manually doing my null checks, I have avoided the onslaught of exceptions, and get the large performance boost.


While that is one large workflow difference, often the ResolvingUsing is used for custom logic that occurs during the mapping, while the MapFrom is generally reserved for flattening operations. If you expect to never have a null, then you may consider using ResolveUsing in order to get an exception that bubbles up when it occurs, and lets you know there is likely a problem. This way the problem is not hidden from you with the large performance hit on the side.



你可能感兴趣的:(ASP.NET,MVC)