views:

596

answers:

1

Hi there,

I have been using automapper pretty successfully lately but i have come across a small problem for mapping the Dest to a variable not a available in the Src.... An example explains it better.. basically i am mapping from dest to src as per instructions .. all working well but i need to now map a destination to a variable named reservationNumber which is local variable not part of ORDER ... anyone know how to do this??

I am using automapper to map from order to reservation for use in linq2sql as Reservation is my linq2sql class.

Is the small example, i would appreciate any input.

    string reservationNumber = "1234567890"; // this is the local variable.. It will be dynamic in future..

    Mapper.CreateMap<Order, Reservation>()
            .ForMember(dest => dest.ReservationNumber, reservationNumber // THIS OBVIOUSLY FAILS)
            .ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.name))
            .ForMember(dest => dest.Surname1, opt => opt.MapFrom(src => src.surname1))
            .ForMember(dest => dest.Surname2, opt => opt.MapFrom(src => src.surname2))
            .ForMember(dest => dest.Email, opt => opt.MapFrom(src => src.email))
            .ForMember(dest => dest.Telephone, opt => opt.MapFrom(src => src.telephone))
     ;
            // Perform mapping
            Reservation reservation = Mapper.Map<Order, Reservation>(order);
+2  A: 

Hi Mark,

Try this:

Mapper.CreateMap<Order, Reservation>()
    .ForMember(dest => dest.ReservationNumber, opt => opt.MapFrom(src => reservationNumber));

That MapFrom option takes any Func. Your other options would be to map to an existing destination object, with the reservation number already there. Or, use a custom value resolver (ResolveUsing), if you need to get the reservation number using a custom service or something.

The CreateMap call only needs to happen once per AppDomain, so you may want to check the other two options and see if they fit your needs.

Jimmy Bogard
Thanks, jimmy works a treat!
mark smith