jamiekurtz / WebApi2Book

Example source code that accompanies ASP.NET Web API 2: Building a REST Service from Start to Finish
http://amzn.to/SR46eq
106 stars 66 forks source link

Automapper syntax #6

Open ptoapanta opened 7 years ago

ptoapanta commented 7 years ago

Hi,

I´m working with AutoMapper 5.1, and is different from the version used in the book. For example the definition in the book is something like this Mapper.CreateMap<Task, Models.Task>() .ForMember(opt => opt.Links, x => x.Ignore()) .ForMember(opt => opt.Assignees, x => x.ResolveUsing());

but in the laste version of AutoMapper there is no a CreateMap. I was reading that it´s necessary to initialize the Mapper.

So now with a parent / child structure I´ve an error message saying that the map to the parent class is missing.

The question is how can I work with the new version of AutoMapper?

Thanks.

HCarnegie commented 7 years ago

Hey, the static API is deprecated. Now you don't have to go the long way over the AutoMapperAdapter anymore. Instead of Mapper.CreateMap<,> in the AutoMapperTypeConfiguration, you only use the MappingExpression CreateMap<,> right in the constructor of a derives class of AutoMapper.Profiler. For example:

public class NewTaskToTaskEntity_AutoMapperMappingProfile : Profile
{ public NewTaskToTaskEntity_AutoMapperMappingProfile() { CreateMap<NewTask, Data.Entities.Task>() .ForMember(opt => opt.Version, x => x.Ignore()) .ForMember(opt => opt.CreatedBy, x => x.Ignore()) .ForMember(opt => opt.TaskId, x => x.Ignore()) .ForMember(opt => opt.CreatedDate, x => x.Ignore()) .ForMember(opt => opt.CompletedDate, x => x.Ignore()) .ForMember(opt => opt.Status, x => x.Ignore()) .ForMember(opt => opt.Users, x => x.Ignore()); } } Now you only have to create your mapper out of the configuration in the NinjectConfigurator. I did it this way, couse i wasn't able to do this in the startup sequence like in the static-version:

private void ConfigureAutoMapper(IKernel container) { var mapperConfiguration = new MapperConfiguration(cfg => { cfg.AddProfiles(GetType().Assembly); }); container.Bind<MapperConfiguration().ToConstant(mapperConfiguration).InSingletonScope(); container.Bind().ToMethod(ctx => new Mapper(mapperConfiguration, type => ctx.Kernel.Get(type))); }

Jimmy describes it in his blog: https://lostechies.com/jimmybogard/2016/01/21/removing-the-static-api-from-automapper/