AutoMapper


  AutoMapper 是一个流行的对象映射器,可以将一个对象映射到另一个对象。Fireasy 提供了 AutoMapper 对 对象映射器 的实现。

  修改配置文件如下:

  • .Net Framework 下的 app.config 或 web.config 文件
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <sectionGroup name="fireasy">
      <section name="objMappers" type="Fireasy.Common.Mapper.Configuration.ObjectMapperConfigurationSectionHandler, Fireasy.Common" />
    </sectionGroup>
  </configSections>
  <fireasy>
    <objMappers default="automapper">
      <mapper name="automapper" type="Fireasy.AutoMapper.ObjectMapper, Fireasy.AutoMapper" />
    </objMappers>
  </fireasy>
</configuration>
  • .Net Core 下的 appsettings.json 文件
{
  "fireasy": {
    "objMappers": {
      "default": "automapper",
      "settings": {
        "automapper": {
          "type": "Fireasy.AutoMapper.ObjectMapper, Fireasy.AutoMapper"
        }
      }
    }
  }
}

  使用 MapperUnity 静态类的 AddProfile 方法添加配置类。如下所示:

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);

        MapperUnity.AddProfile<AutoProfile>();
    }
}

public class AutoProfile : Profile
{
     public AutoProfile()
     {
         CreateMap<SysUser, UserDto>().ReverseMap();
        CreateMap<SysModule, ModuleDto>(s => s.Url, 
            s => s.MapFrom(t => "http://www.fireasy.cn/" + t.Url))
          .ReverseMap();
        CreateMap<SysRole, RoleDto>().ReverseMap();
    }
}

  在 .Net Core 应用中可以使用扩展方法 AddAutoMapper 切换到 AutoMapper,同时使用 AddProfile 方法添加配置类。如下所示:

namespace demo
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddFireasy().AddAutoMapper(s =>
            {
                s.AddProfile<AutoProfile>();
                
                //程序集内搜索 Profile
                s.AddProfiles(this.GetType().Assembly);
            });
        }
    }

    public class AutoProfile : Profile
    {
        public AutoProfile()
        {
            CreateMap<SysUser, UserDto>().ReverseMap();
            CreateMap<SysModule, ModuleDto>(s => s.Url, 
                s => s.MapFrom(t => "http://www.fireasy.cn/" + t.Url))
              .ReverseMap();
            CreateMap<SysRole, RoleDto>().ReverseMap();
        }
    }
}