当映射依赖于先前的映射配置时,如何执行映射?

时间:2017-04-28 09:29:06

标签: automapper

以下志愿者与志愿者之间的映射。 IVolunteerViewDTO工作得非常好。我可以调用REST api并接收使用AutoMapper映射的IVolunteerViewDTO列表。但是,我无法弄清楚如何使用IRegistrationDTO进行注册。 AutoMapper抛出异常并说:InvalidCastException: Unable to cast object of type 'Proxy<RSMuseum.Services.DTOs.IVolunteerViewDTO_RSMuseum.Services_Version=1.0.0.0_Culture=neutral_PublicKeyToken=null>' to type 'RSMuseum.Services.DTOs.VolunteerViewDTO'.

    public IMapper GetMapper()
    {
        var mc = new MapperConfiguration(cfg =>
        {
            cfg.CreateMap<Volunteer, IVolunteerViewDTO>()
              .ForMember(dest => dest.GuildName,
             opts => opts.MapFrom(src => src.Guilds.Select(x => x.GuildName)))
             .ForMember(dest => dest.FirstName,
             opts => opts.MapFrom(src => src.Person.FirstName))
              .ForMember(dest => dest.LastName,
             opts => opts.MapFrom(src => src.Person.LastName));

            cfg.CreateMap<Guild, IGuildDTO>();

            cfg.CreateMap<Repository.Entities.Registration, IRegistrationDTO>()
                .ForMember(dest => dest.Guild,
                    opts => opts.MapFrom(src => src.Guild))
            .ForMember(dest => dest.Volunteer,
                opts => opts.MapFrom(src => src.Volunteer));
        });

        mc.AssertConfigurationIsValid();

        IMapper m = new Mapper(mc, t => _container.GetInstance(t));

        return m;
    }

dest.Volunteer是DTO,src.Volunteer是实体本身。当我在RegistrationDTO注释出VolunteerDTO的需求时,一切都很好,完全没有例外。问题是如何解决。

0 个答案:

没有答案