0

Source class:

pubilc class Source {
    public string SourceProperty { get; set; }
}

Destination class

pubilc class Destination {
    public string SourceProperty { get; set; }
    public string ValueFromMappingContext { get; set; }
}

AutoMapper profile

public class CustomProfile : Profile {
    public CustomProfile(){
        CreateMap<Source, Destination>()
    }
}

This is where my mapping takes place


string valueFromMappingContext = "This Value is common for all items in the destination collection";

IEnumerable<Source> sourceItems = GetSourceItems();

IEnumerable<Destination> destinationItems = _mapper.Map<IEnumerable<Destination>>(sourceItems);

// I don't want to do this. this is the part I'm looking to replace:
destinationItems.ForAll(d => d.ValueFromMappingContext = valueFromMappingContext);

Ccurrently I have another loop right after the Map() method to populate this property, but I feel like there should be an AutoMapper feature to do this.

If it was a single item, I could probably use AfterMap method, but this won't work for an IEnumerable. If the ValueFromMappingContext was known at creation of CustomProfile, or could be something that can be derived from Source, I could probably use ForMember within my profile.

But ValueFromMappingContext is only known at the context where the actual mapping takes place. And its not part of the Source object.

How can I map valueFromMappingContext to each destinationItem.ValueFromMappingContext property in the destinationItems collection using AutoMapper features? I'm using AutoMapper 10.0

Nandun
  • 1,802
  • 2
  • 20
  • 35
  • 2
    https://stackoverflow.com/a/31754133/10608418 might this be a solution you're looking for? –  Nov 17 '20 at 16:48
  • Thank you @Knoop, this is the specific answer from that thread that did the trick: https://stackoverflow.com/a/60019540/1184584 – Nandun Nov 17 '20 at 17:22

0 Answers0