Mar*_*Ene 5 asp.net asp.net-mvc automapper
我的网站上的 Automapper 有问题,我找不到解决方案。我创建了一个名为 AutoMapperProfile 的类,我想在其中放置我所有的地图
public class AutoMapperProfile: Profile
{
private readonly IConfiguration _mapper;
public AutoMapperProfile(IConfiguration mapper)
{
_mapper = mapper;
}
protected override void Configure()
{
base.Configure();
_mapper.CreateMap<SlideDTO, Slide>();
_mapper.CreateMap<Slide, SlideDTO>();
}
}
Run Code Online (Sandbox Code Playgroud)
出于 DI 目的,我使用 Ninject,因此我在 NinjectWebCommon 中添加了以下绑定:
kernel.Bind<IMappingEngine>().ToMethod(ctx => Mapper.Engine);
kernel.Bind<IConfigurationProvider>().ToMethod(x => Mapper.Engine.ConfigurationProvider);
Run Code Online (Sandbox Code Playgroud)
控制器看起来像这样:
private readonly ISlideRepository slideRepository;
private readonly IMappingEngine mappingEngine;
public HomeController(
ISlideRepository slideRepository,
IMappingEngine mappingEngine)
{
this.slideRepository = slideRepository;
this.mappingEngine = mappingEngine;
}
[HttpGet]
public ActionResult Index()
{
var model = new IndexViewModel();
var slide = slideRepository.GetSlide();
model.Slide = mappingEngine.Map<SlideDTO, Slide>(slide);
return View(model);
}
Run Code Online (Sandbox Code Playgroud)
当我从 SlideDTO 映射到 Slide 时,出现以下错误:
Missing type map configuration or unsupported mapping.
Run Code Online (Sandbox Code Playgroud)
所以我最好的猜测是我没有正确进行绑定,以便 Automapper 可以看到我的地图,但我不确定如何修复它。
您不需要注入IConfiguration到AutoMapperProfile,它已经继承CreateMap了 的方法Profile。
确保AutoMapperProfile有一个无参数构造函数,如下所示:
public class AutoMapperProfile : Profile
{
protected override void Configure()
{
this.CreateMap<SlideDTO, Slide>();
this.CreateMap<Slide, SlideDTO>();
}
}
Run Code Online (Sandbox Code Playgroud)
然后您需要确保 AutoMapper 了解此配置文件,具体方法如下:
Mapper.Engine.ConfigurationProvider.AddProfile<AutoMapperProfile>();
Run Code Online (Sandbox Code Playgroud)
AddProfile请注意,您可以在任何上调用该方法IConfigurationProvider(如果您决定不使用全局ConfigurationProvider和Engine)。
| 归档时间: |
|
| 查看次数: |
292 次 |
| 最近记录: |