Home > Back-end >  AutoMapper: Convert Type for one Property
AutoMapper: Convert Type for one Property

Time:06-13

I use the following two classes for Entity and DTO:

public class VehicleEntity {
    public int Id { get; set; }
    public string AddressNumber { get; set; }
    public string VehicleNumber { get; set; }
    public string Brand { get; set; }
    public string NumberPlacesStr { get; set; }
}

public class VehicleDto {
    public int Id { get; set; }
    public string AddressNumber { get; set; }
    public string VehicleNumber { get; set; }
    public string Brand { get; set; }
    public int NumberPlaces { get; set; }
}

For Mapping, I use AutoMapper like

configuration.CreateMap<VehicleEnity, VehicleDto>()

This is working great. But the Property NumberPlacesStr is a string in the VehicleEntity and should be mapped to the int property NumberPlaces in the VehicleDTO. How can I configure this speciality?

CodePudding user response:

Use .ForMember() by specifying the source and destination property. Automapper will handle the casting from string to int.

configuration.CreateMap<VehicleEntity, VehicleDto>()
                .ForMember(dest => dest.NumberPlaces, opt => opt.MapFrom(src => src.NumberPlacesStr));

However, the above approach may not work correctly if NumberPlacesStr is unable to be cast as int.

You may consider using the Custom Value Resolver for safe mapping and casting.

public class VehicleNumberPlacesResolver : IValueResolver<VehicleEntity, VehicleDto, int>
{
    public int Resolve(VehicleEntity source, VehicleDto destination, int member, ResolutionContext context)
    {
        try
        {
            return Int32.Parse(source.NumberPlacesStr);
        }
        catch
        {
            return default;
        }
    }
}
configuration.CreateMap<VehicleEntity, VehicleDto>()
                .ForMember(dest => dest.NumberPlaces, opt => opt.MapFrom<VehicleNumberPlacesResolver>());

Sample .NET Fiddle


References

Projection - AutoMapper

Custom Value Resolvers - AutoMapper

  • Related