Using Automapper (.net C #) to map to a variable not in Src for use in linq2sql classes?

I have been using automapper quite successfully lately, but I ran into a small problem to map Dest to a variable not available in Src. An example explains it better .. basically I am mapping from dest src as per the instructions .. everything works well, but I need to now map the destination to a variable called reserveNumber which is a local variable not part of the ORDER ... anyone- does anyone know how to do this?

I am using automapper to display from order to reservation for use in linq2sql since reservation is my linq2sql class.

Is a 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


source to share


1 answer


Try the following:

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

      



This MapFrom option accepts any Func. Your other parameters will be mapping to an existing destination where the reservation number already exists. Or use a custom value converter (ResolveUsing) if you need to get the reservation number using a custom service or something.

The CreateMap call is only required once per AppDomain, so you can check the other two parameters and see if they suit your needs.

+3


source







All Articles