TL;DR: Is there a way to create a sort of convention or prefix rule that would use the source or destination class names as prefix for some field mappings using AutoMapper 12.0?
I'm experimenting with AutoMapper 12.0 in a dotnet core 6 project and the entity classes use the entity name as prefix for their keys (eg.: Person
class has a PersonId
property, which is mapped to the primary key in DB), but the API side has DTOs that don't include those prefixes:
// Entity definition
public class Person
{
public int PersonId { get; set; }
public string Name { get; set; }
// ...
}
// API response definition
public class PersonDetails
{
public int Id { get; set; }
public string Name { get; set; }
// ...
}
The way I configured my mappings to make it work was to manually define the mapping for the IDs using .ForMember(...)
, but that requires me to do that for every single entity and DTO combination:
public class EntityToViewModelMappingProfile : Profile
{
public EntityToViewModelMappingProfile() : base(nameof(EntityToViewModelMappingProfile))
{
CreateMap<Person, PersonDetails>()
.ForMember(p => p.Id, o => o.MapFrom(p => p.PersonId))
.ReverseMap();
// ...
// the same code for all of my entities :(
}
}
I'm looking for a way to avoid a bunch of boilerplate code and have a generic rule that would work for all of my entities without having to write custom mappings for all of them.
Even though I have custom mappings for other fields, that case is the one that seems to be a fit for a custom convention, but I couldn't find a way to implement one that would give me access to the destination and source type names to be able to use them as prefixes.
As Lucian Bargaoanu pointed out in the comments, there is a similar question for an earlier version of AutoMapper here and it suggests using:
Mapper.Initialize(exp =>
{
exp.CreateMap<User, UserDto>();
exp.ForAllMaps((typeMap, mappingExpression) =>
mappingExpression.ForMember("Id", o=>o.MapFrom(typeMap.SourceType.Name + "Id"))
);
});
AutoMapper 12.0 seems to not support ForAllMaps
, from what I researched in their docs. Is there a way to achieve the same with 12.0?