简体   繁体   中英

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

When trying to map a list of Source to a list of Destination automapper is overriding the Id so it becomes 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);

I've also tried using ValidateMemberList(MemberList.None) but the effect is the same. This ONLY happens when the objects are in a list. Mapping between two objects works as expected. Am I missing some configuration option?

EDIT: checking with make id in visual studio it seems it's replacing the objects in the destination with new ones instead of mapping values, is there any way to change this behavior or have it keep all non mapped properties from the initial destination object?

It seems unintuitive to me but currently this is the intended behavior so I decided to just iterate and map each item individually.

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

For my use case I didn't think it was worth it to add a new a dependency on AutoMapper Collection and then also try to make it work with indexes somehow.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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