AutoMapper:更新现有集合

AutoMapper: to update an existing collection

使用此映射现有实体相当简单

Mapper.Map<Source, Destination>(source, destination);

但我想更新现有的集合,例如:

        var class1List = new List<Class1>
        {
            new Class1 { Id = 1, Name = "Name1", Text = "Text1"},
            new Class1 { Id = 2, Name = "Name2", Text = "Text2"},
            new Class1 { Id = 3, Name = "Name3", Text = "Text3" },
        };

        var class2List = new List<Class2>
        {
            new Class2 { Id = 1, Name = "a" },
            new Class2 { Id = 2, Name = "b" },
        };

        ObjectMapper.Map<List<Class1>, List<Class2>>(class1List, class2List)
            .Key("Id"); //here I'd supposedly specify a key to map the objects but there is no such a method
        /*
           the desired result is an updated collection with one new item:
            class2List = new List<Class2>
            {
                new Class2 { Id = 1, Name = "Name1", Text = "Text1"},  //this is updated by Id
                new Class2 { Id = 2, Name = "Name2", Text = "Text2"},  //this is updated by Id
                new Class2 { Id = 3, Name = "Name3", Text = "Text3" }, //this is a new object because there were no matching Id in the list
            }
        */

是否可以通过 AutoMapper 执行此操作? 因为没有指定Key去映射,它实际上只是returns一个与初始集合无关的3个新Class2项目的集合。

来自评论:

The fine manual 对于 automapper 集合意味着您在其他地方配置 ID 等效性,例如像

mapperconfig.CreateMap<Class1, Class2>().EqualityComparison((c1, c2) => c1.Id == c2.Id);

然后您可以将 Class1 的集合映射到 Class2 的集合