按照惯例从 Collection<T> 映射到 Collection<T>

Mapping from Collection<T> to Collection<T> by convention

是否可以按照惯例从 Collection 类型的 属性 映射到 Collection 类型的另一个 属性 而无需显式定义映射?

class CollectionExample {
    public static void Example() {
        var config = new MapperConfiguration(cfg =>
        {
            cfg.CreateMap<Foo, FooDto>()
                //.ForMember(dest => dest.Items, member => member.MapFrom(src => src.Items))
            ;
        });
        var mapper = config.CreateMapper();

        var foo = new Foo() {
            Items =
            {
                new Foo(),
                new Foo(),
                new Foo()
            }
        };

        var fooDto = mapper.Map<Foo, FooDto>(foo);

        Debug.Assert(fooDto.Items.Count == foo.Items.Count, $"There are only {fooDto.Items.Count} items in the dto object but we expected {foo.Items.Count} items.");
    }

    class Foo {
        public Collection<Foo> Items { get; } = new Collection<Foo>();
    }

    class FooDto {
        public Collection<FooDto> Items { get; } = new Collection<FooDto>();
    }
}

当我取消对 ForMember(..) 的注释时,这有效。我是否遗漏了基于约定的方法的某些内容?

您需要 setter 或 MapFrom,以您喜欢的为准 :) 10 之前的版本就是这种情况。检查评论中的 link 以了解行为版本 10.