繁体   English   中英

Automapper 仅在映射对象列表时覆盖不在源中的目标值

[英]Automapper overrinding destination values that are not in source ONLY when mapping lists of objects

当尝试 map 时,源列表到目标自动映射器列表正在覆盖 Id,因此它变为 00000000-0000-0000-0000-000000000000。

            var configuration = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap<Source, Destination>()
                    .ForMember(d => d.Name, opt => opt.MapFrom(dest => dest.Name))
                    .ForAllOtherMembers(opt => opt.Ignore());
            });

            var sourceList = new List<Source>
            {
                new Source
                {
                    Name = "name1"
                },
                new Source
                {
                    Name = "name2",
                },
                new Source
                {
                    Name = "name3"
                }

            };

            var destList = new List<Destination>
            {
                new Destination
                {
                    Id = Guid.NewGuid()
                },
                new Destination
                {
                    Id = Guid.NewGuid()
                },
                new Destination
                {
                    Id = Guid.NewGuid()
                }
            };
            var mapper = new Mapper(configuration);
            var result = mapper.Map(sourceList, destList);

我也尝试过使用ValidateMemberList(MemberList.None)但效果是一样的。 这只发生在对象在列表中时。 两个对象之间的映射按预期工作。 我错过了一些配置选项吗?

编辑:在visual studio中检查make id,它似乎用新的对象而不是映射值替换目标中的对象,有没有办法改变这种行为或让它保留来自初始目标object的所有非映射属性?

这对我来说似乎不直观,但目前这是预期的行为,所以我决定单独迭代和 map 每个项目。

for (var i = 0; i < sourceList.Count; i++)
{
    var source = sourceList[i];
    var destination= destList[i];
    mapper.Map(source, destination);
}

对于我的用例,我认为在AutoMapper Collection上添加一个新的依赖项然后尝试以某种方式使其与索引一起使用是不值得的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM