从Collection 映射到Collection 按照惯例

问题描述 投票:0回答:1

是否可以通过约定从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(..)时,此方法有效。我是否缺少基于约定的方法?

c# automapper
1个回答
0
投票

您需要设置器或MapFrom,以您喜欢的为准:)

© www.soinside.com 2019 - 2024. All rights reserved.