我在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/