c# - Automapper 5.0全局配置

标签 c# model-view-controller automapper

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

但我无法使用 Mapper.Map<Hospital, MongoHospital>在我的 Controller 。它抛出一个异常,没有定义映射。它 在以前版本的 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();
    }
}

尝试按如下方式访问此 map

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 阶段。

关于c# - Automapper 5.0全局配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37348788/

相关文章:

c# - 将 ODATA $expand 查询选项与 WebAPI 和 ViewModel 结合使用

c# - 编译大型 ASP .NET 应用程序的可用选项

c# - 以下返回值的有效 C# 数据类型是什么,或者我如何访问内部属性?

c# - 如何阻塞直到异步作业完成

ios - 在 View Controller 之间传递数据

c# - 为 ASP .NET MVC 创建单元测试时出现的问题

javascript - 在 Javascript 中访问 MVC 服务器端变量

ios - MVC, Controller 和模型之间的区别?

c# - AutoMapper 不映射子属性

c# - AutoMapper - 将目标字符串设置为 null 实际上使其成为 string.Empty