Automapper 5.0全局配置 [英] Automapper 5.0 global configuration

查看:98
本文介绍了Automapper 5.0全局配置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用App_Start文件夹中AutoMapperConfig.cs中的以下代码.一世 在Global.asax中将其初始化为AutoMapperConfiguration.Configure()

I am using the code below in AutoMapperConfig.cs in App_Start folder. I initialized it in Global.asax as AutoMapperConfiguration.Configure()

但是我无法在我的电脑中使用Mapper.Map<Hospital, MongoHospital> 控制器.没有定义任何映射是一个例外.它 在支持Automapper的早期版本中工作 Mapper.CreateMap<>方法.我很困惑如何使用 MapperConfiguration实例.

But I am unable to use the Mapper.Map<Hospital, MongoHospital> in my controller. It is throwing an exception that no mappings are defined. It was working in previous versions of Automapper which were supporting Mapper.CreateMap<> methods. I am confused how to use MapperConfiguration instance.

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

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

尝试按以下方式访问此地图

Trying to access this map as below

Mapper.Map<IEnumerable<Hospital>, IEnumerable<MongoHospital>>(hospitalsOnDB);

推荐答案

在这种情况下,您是否真的需要使用配置文件?如果没有,您可以尝试像这样初始化Mapper:

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()));
    }
}

希望这会有所帮助.如果您使用的是AutoMapper 5.0,请记住,此时它仍处于beta-1状态.

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

这篇关于Automapper 5.0全局配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆