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