Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Automapper 11, string to Uri no longer works

since upgrading to automapper 11 trying to map a string to an Uri no longer works

Entity

public sealed class Website
{
    public int Id { get; set; }
    public string Name {get; set; }
    public string BaseAddress { get; set; }
}

object I’m mapping to

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

public sealed class WebsiteDto
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Uri BaseAddress { get; set; }
}

mapping profile contains

CreateMap<Website, WebsiteDto>();

and how I’m calling it

_mapper.Map<List<WebsiteDto>>(listOfWebsiteEntities);

This was working fine before upgrading to 11, I think it might be a bug but before I raise it as an issue Automapper suggests raising a question here, am I missing something?

after downgrading to automapper 10.1.1 it works again. the upgrade guide doesn’t seem to mention anything related to this

>Solution :

This happens due to next breaking change:

System.ComponentModel.TypeConverter is no longer supported
It was removed for performance reasons. So it’s best not to use it anymore. But if you must, there is a sample in the test project.

You can bring it back by adding TypeConverterMapper to mappers (or just create a mapping from string to Uri and back, which, I would say, is better option):

var cfg = new MapperConfiguration(cfg => cfg.Internal().Mappers.Insert(0, new TypeConverterMapper()))

public class TypeConverterMapper : ObjectMapper<object, object>
{
    public override bool IsMatch(TypePair context)
    {
        return GetConverter(context.SourceType).CanConvertTo(context.DestinationType) ||
            GetConverter(context.DestinationType).CanConvertFrom(context.SourceType);
    }

    public override object Map(object source, object destination, Type sourceType, Type destinationType, ResolutionContext context)
    {
        var typeConverter = GetConverter(sourceType);
        return typeConverter.CanConvertTo(destinationType) ? typeConverter.ConvertTo(source, destinationType) : GetConverter(destinationType).ConvertFrom(source);
    }
    private TypeConverter GetConverter(Type type) => TypeDescriptor.GetConverter(type);
}

Related github issue

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading