I have a class Destination
with a constructor that takes parameters, and I’m trying to map a Source
object to Destination
using AutoMapper. The mapping for Id
works fine, but the mapping for InStore
doesn’t seem to work when I use a custom mapping. Here is my code:
using AutoMapper;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, Destination>()
.ForMember(dest => dest.Id, opt => opt.MapFrom(src => int.Parse(src.Id)))
.ForMember(dest => dest.InStore, opt => opt.MapFrom(src => src.InStore == "1"));
});
var mapper = config.CreateMapper();
var source = new Source { Id = "123", InStore = "1" };
var destination = mapper.Map<Destination>(source);
Console.WriteLine($"Id: {destination.Id}, InStore: {destination.InStore}");
public class Source
{
public string Id { get; set; }
public string InStore { get; set; }
}
public class Destination
{
public int Id { get; private set; }
public bool InStore { get; private set; }
public Destination(int id, bool inStore)
{
Id = id;
InStore = inStore;
}
}
Throw exception:
AutoMapper.AutoMapperMappingException: 'Error mapping types.'
FormatException: String '1' was not recognized as a valid Boolean.
When I remove the parameterized constructor from Destination
, the mapping works correctly. Also, when var source = new Source { Id = "123", InStore = "true" };
is used, the mapping also works. These observations confuse me as to why the mapping fails with a constructor present and when InStore
is set to "1"
.