AutoMapper 8 ConvertUsing(Complex,string)

3k Views Asked by At

I am trying to clean a string EmailInstructions during a mapping but it fails when I call Mapper.Configuration.AssertConfigurationIsValid(); with:

No coercion operator is defined between types 'System.String' and 'ElectionViewModel'

Here's my setup:

public class AutoMapperConfiguration
{
    public static void Configure()
    {
        Mapper.Initialize(x =>
        {
            x.AddProfile<SystemProfile>();
        });

        Mapper.Configuration.AssertConfigurationIsValid();
    }
}

My Mapper:

public class SystemProfile : Profile
{
    public SystemProfile()
    {
        CreateMap<ElectionViewModel, Election>()
            .ForMember(x => x.EmailInstructions, y => 
               y.ConvertUsing(new EmailInstructionVariablesCleanerConverter()))

My ValueConverter

public class EmailInstructionVariablesCleanerConverter : IValueConverter<ElectionViewModel, string>
{
    public string Convert(ElectionViewModel source, ResolutionContext context)
    {
        return CleanVariables(source.EmailInstructions);

    }
    private static string CleanVariables(string text)
    {
        return Clean the text here
    }
}
1

There are 1 best solutions below

0
Suncat2000 On

I was trying to solve a similar error but I have discovered the cause of yours along the way. I offer my observations here by filling in some missing details to assist others who still may be confused.

You didn't include your source and destination classes. Because of AutoMapper's behavior and the error you reported, I assumed that your destination type Election includes at least the following member:

public class Election
{
    public string EmailInstructions { get; set; }
}

When you created your mapping for that member using the map expression

CreateMap<ElectionViewModel, Election>()
    .ForMember(x => x.EmailInstructions, y => y.ConvertUsing(new EmailInstructionVariablesCleanerConverter()))

AutoMapper matched the destination and source EmailInstructions members, then selected your source string EmailInstructions to pass to EmailInstructionVariablesCleanerConverter, which was defined to expect an ElectionViewModel type as the source object. Because there was no conversion operator defined on either type that would implement coercion from a string into the required ElectionViewModel object, the expression compiler threw the "no coercion operator" exception.

Given those details, @Lucian made the suggestion that you replace your converter to something more appropriate: a value transformer to modify your source string; or, a value converter to convert the source string into a new string.