Automapper 5.0 global configuration

人盡茶涼 提交于 2019-12-03 21:11:17

Do you actually need to use a Profile in this scenario? If you don't, you can try just initialising the Mapper like this:

public static class AutoMapperConfiguration
{
    public static void Configure()
    {
        Mapper.Initialize(
            config =>
            {
                config.CreateMap<Hospital, MongoHospital>()
                    .ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.Id.ToString()));
            });
    }
}

However, if you would like to still register a Profile, you can do this:

public static class AutoMapperConfiguration
{
    public static void Configure()
    {
        Mapper.Initialize(
            cfg =>
            {
                cfg.AddProfile<HospitalProfile>();
            }
        );
    }
}

public class HospitalProfile : Profile
{
    protected override void Configure()
    {
        CreateMap<Hospital, MongoHospital>()
                .ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.Id.ToString()));
    }
}

Hope this helps. If you're using AutoMapper 5.0, remember that this is still at beta-1 at this point in time.

You can use this with AutoMapper 5.2.

Your Profile class as below

public class MapperProfile: Profile
{
    public MapperProfile()
    {
        CreateMap<Hospital, MongoHospital>().ReverseMap();
    }

}

Then in your Global.asax

     protected void Application_Start()
     {
       //Rest of the code 
       Mapper.Initialize(c => c.AddProfiles(new string[] { "DLL NAME OF YOUR PROFILE CLASS" }));
     }

Now when you need to create an instance

AutoMapper.Mapper.Instance.Map<MongoHospital, Hospital>(source, new Hospital());

Hope this helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!