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
}
}
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
Electionincludes at least the following member:When you created your mapping for that member using the map expression
AutoMapper matched the destination and source
EmailInstructionsmembers, then selected your source stringEmailInstructionsto pass toEmailInstructionVariablesCleanerConverter, which was defined to expect anElectionViewModeltype as the source object. Because there was no conversion operator defined on either type that would implement coercion from astringinto the requiredElectionViewModelobject, 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.