80

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?

d219
  • 2,707
  • 5
  • 31
  • 36
Rick Eyre
  • 2,355
  • 4
  • 20
  • 26

1 Answers1

153
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"));
Martin
  • 6,436
  • 1
  • 17
  • 10
mfanto
  • 14,168
  • 6
  • 51
  • 61
  • Is there good documentation somewhere? All I found was the small wiki on the GitHub page, but that's not much. – Rick Eyre Oct 30 '12 at 20:20
  • As far as I know, the best documentation is at https://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. – mfanto Oct 30 '12 at 20:31
  • 2
    The new API replaced this with MapFrom https://docs.automapper.org/en/stable/8.0-Upgrade-Guide.html?highlight=value#usevalue `Mapper.CreateMap() .ForMember(dest => dest.Member, opt => opt.MapFrom("THIS STRING"));` – Wahid Bitar Jan 08 '19 at 09:27
  • 14
    @WahidBitar Thank you for quoting the source. This is a more accurate example: `.ForMember(dest => dest.Member, opt => opt.MapFrom(src => "THIS STRING"))` – Onosa Jan 08 '19 at 16:43
  • 1
    might as well put it in the form `Mapper.CreateMap() .ForMember(dest => dest.Member, opt => opt.MapFrom(_ => "THIS STRING"));`, "omitting" the src parameter since it's not used – Alessandro Lendaro Jan 12 '22 at 18:56