When using Automapper 3.3.1 or 4.2.1 my code is running fine.
But after upgrade to 5.2.0 I get ArgumentException: "Type 'System.String' does not have a default constructor" in AutoMapper.QueryableExtensions.ExpressionBuilder.DestinationConstructorExpression.
We have a legacy database that supports several languages and in our EF6 model we us a LocalizedString complex type to hold all the translated values for each string property. Based on this article.
Sample code:
static void Main(string[] args)
{
Mapper.Initialize(p =>
{
CreateCustomMappingForLocalizedString(p);
p.CreateMap<Country, CountryViewModel>();
}
);
var db = new DemoContext();
var countries = db.Country.ProjectTo<CountryViewModel>(new {lang = "nb"}).ToList();
foreach (var c in countries)
Console.WriteLine($"{c.CountryId} : {c.CountryCode} : {c.CountryName}");
Console.WriteLine("Press <ENTER> to continue");
Console.ReadLine();
}
And the custom mapping of LocalizedString is
public static void CreateCustomMappingForLocalizedString(IMapperConfigurationExpression cfg)
{
string lang = null;
// Create MAP for LINQ Projections
cfg.CreateMap<LocalizedString, string>()
.ProjectUsing(src =>
lang == "en"? src.ValueEn :
lang == "da"? src.ValueDa :
lang == "nn"? src.ValueNnNo :
lang == "sv"? src.ValueSv :
lang == "de" ? src.ValueDe :
lang == "fi"? src.ValueFi :
lang == "se"? src.ValueSeNo :
src.ValueNo);
cfg.CreateMap<LocalizedString, string>()
.ConvertUsing(src =>
Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName == "en" ? src.ValueEn :
Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName == "da" ? src.ValueDa :
Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName == "nn"? src.ValueNnNo :
Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName == "sv"? src.ValueSv :
Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName == "de"? src.ValueDe :
Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName == "fi"? src.ValueFi :
Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName == "se"? src.ValueSeNo :
src.ValueNo);
}
The only change in moving to 5.2.0 from 4.2.0 is to change parameter type in CreateCustomMappingForLocalizedString from IMapperConfiguration to IMapperConfigurationExpression.
Am I doing something wrong here with Automapper 5.2.0 or is this a bug in Automapper?
I have put a small sample solution with separate projects for versions 3.3.1, 4.2.1 and 5.2.0 on my GitHub repo.