Automapper UseDestinationValue 不适用于 List

Automapper UseDestinationValue does not work for List

我正在尝试将 List<Sensor> 映射到 List<Beer>,我不希望 beer.Namesensor.Name 覆盖。我的代码可以很好地映射一对一的简单对象,但不适用于 List

        var config = new MapperConfiguration(cfg => {
            cfg.CreateMap<Sensor, Beer>()
            .ForMember(x => x.Name, opt => { opt.UseDestinationValue(); })
            .EqualityComparison((src, dest) => src.Id == dest.Id);
        });
        var mapper = config.CreateMapper();

        var beer1 = new Beer { Id = 1, Name = "test" };
        var sensor1 = new Sensor { Id = 1, Name = null, Temperature = 20 };
        mapper.Map(sensor1, beer1);
        // beer1.Name == "test" // looks fine!

        var beerList = new List<Beer> { new Beer { Id = 2, Name = "test" } };
        var sensorList = new List<Sensor> { new Sensor { Id = 2, Name = null, Temperature = 20 } };
        mapper.Map(sensorList, beerList);
        // beerList[0].Name == null // it does not work, I wanted it to be "test" as above

您的配置中缺少的位是 cfg.AddCollectionMappers(); 添加后所有映射都按您预期的方式工作。

var config = new MapperConfiguration(cfg => {
    cfg.AddCollectionMappers();
    cfg.CreateMap<Sensor, Beer>()
        .ForMember(x => x.Name, opt => { opt.UseDestinationValue(); })
        .EqualityComparison((src, dest) => src.Id == dest.Id);
});