gpt4 book ai didi

c# - Automapper 5.0全局配置

转载 作者:行者123 更新时间:2023-11-30 20:36:02 25 4
gpt4 key购买 nike

我在 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);

最佳答案

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com