Conditional Property Population for DTOs In C# Using AutoMapper
One of the neat things I’ve been able to do with AutoMapper is conditionally populate members of a DTO. Say I’ve got an internal data structure that’s multi-faceted — one of those “ItemType” and “ItemId” kind of tables that can serve the same purpose for multiple entities in the database.
On my dto, I’ve got ItemType and ItemId, but I also put in the dto for Entity1 and Entity2 (mutually exclusive).
In AutoMapper, I set up an IValueResolver<DestinationDto, object, Entity1>. I can inject my IEntity1Repository and use it during resolution.
In resolution, I check the item type of the destination dto: if it’s Entity1, I go grab the data model from the database and convert it to the Entity1 dto using the provided ResolutionContext.Mapper.
To use it, I use ResolveUsing:
var map1 = CreateMap<Data.DestinationDataModel, DTO.DestinationDto>();
map1.ForMember(d => d.Entity1, opt => opt.ResolveUsing<DestinationDataModelEntity1ValueResolver>());