Automapper 5.0全局配置

Automapper 5.0 global configuration

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

但是我无法使用 Mapper.Map<Hospital, MongoHospital> 控制器。它抛出未定义映射的异常。它 在支持的 Automapper 的早期版本中工作 Mapper.CreateMap<> 方法。我很困惑如何使用 MapperConfiguration实例。

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

正在尝试按如下方式访问此地图

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

你真的需要在这种情况下使用配置文件吗?如果你不这样做,你可以尝试像这样初始化映射器:

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

但是,如果您仍想注册个人资料,可以这样做:

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。

您可以将它与 AutoMapper 5.2 一起使用。

您的个人资料class如下

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

}

然后在你的Global.asax

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

现在您需要创建一个实例

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

希望对您有所帮助。