【发布时间】:2016-05-20 14:04:42
【问题描述】:
我在App_Start 文件夹中的AutoMapperConfig.cs 中使用以下代码。我
在Global.asax 中将其初始化为AutoMapperConfiguration.Configure()
但我无法在我的
控制器。它抛出一个没有定义映射的异常。它
在支持的 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);
【问题讨论】:
-
您的配置文件应该调用 CreateMap,而不是创建整个配置对象。
-
MapperConfiguration 有什么用?它在哪里完美契合?
标签: c# model-view-controller automapper