Conditional Property Population for DTOs In C# Using AutoMapper

Adam Skinner
Jul 24, 2017 · 1 min read

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>());

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade