How to Map String Literal to Destination Property
Asked Answered
D

1

84

I'd like to be able to do something like this using automapper:

Mapper.CreateMap<Source, Destination>()
    .ForMember<d => d.Member, "THIS STRING">();

I'd like d.Member to always be "THIS STRING" and not be mapped from any particular member from the source model. Putting a string field in the source model with "THIS STRING" as it's value is also not an option.

Does AutoMapper support these kinds of things in any way?

Diacaustic answered 30/10, 2012 at 20:4 Comment(0)
E
162
Mapper.CreateMap<Source, Destination>()
    .ForMember(dest => dest.Member, opt => opt.UseValue<string>("THIS STRING"));

Starting with version 8.0 you have to use the following:

Mapper.CreateMap<Source, Destination>()
    .ForMember(dest => dest.Member, opt => opt.MapFrom(src => "THIS STRING"));
Elkins answered 30/10, 2012 at 20:7 Comment(5)
Is there good documentation somewhere? All I found was the small wiki on the GitHub page, but that's not much.Diacaustic
As far as I know, the best documentation is at github.com/AutoMapper/AutoMapper/wiki What's nice about AutoMapper is it's pretty straight forward. opt.MapFrom() to map from properties, opt.UseValue() to use a static value, and opt.ResolveUsing<>() to use a custom resolver.Elkins
The new API replaced this with MapFrom docs.automapper.org/en/stable/… Mapper.CreateMap<Source, Destination>() .ForMember(dest => dest.Member, opt => opt.MapFrom("THIS STRING"));Turbinal
@WahidBitar Thank you for quoting the source. This is a more accurate example: .ForMember(dest => dest.Member, opt => opt.MapFrom(src => "THIS STRING"))Acephalous
might as well put it in the form Mapper.CreateMap<Source, Destination>() .ForMember(dest => dest.Member, opt => opt.MapFrom(_ => "THIS STRING"));, "omitting" the src parameter since it's not usedAllmon

© 2022 - 2024 — McMap. All rights reserved.