Automapper 5.2.0和EF6投影抛出异常 - 错误?

时间:2016-11-29 20:37:10

标签: c# entity-framework entity-framework-6 automapper automapper-5

使用Automapper 3.3.1或4.2.1时,我的代码运行正常。

但升级到5.2.0后,我得到了ArgumentException:“AutoMapper.QueryableExtensions.ExpressionBuilder.DestinationConstructorExpression中的类型'System.String'没有默认构造函数”。

我们有一个支持多种语言的遗留数据库,在我们的EF6模型中,我们使用LocalizedString复杂类型来保存每个字符串属性的所有翻译值。基于此article

示例代码:

    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();
    }

LocalizedString的自定义映射是

    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);
    }

从4.2.0迁移到5.2.0的唯一变化是将CreateCustomMappingForLocalizedString中的参数类型从IMapperConfiguration更改为IMapperConfigurationExpression。

我是否在使用Automapper 5.2.0时遇到了问题,或者这是Automapper中的错误?

我已经在我的GitHub repo上为版本3.3.1,4.2.1和5.2.0提供了一个小样本解决方案和单独的项目。

0 个答案:

没有答案