按照约定从Collection <T>映射到Collection <T>

时间:2019-11-07 15:43:03

标签: c# automapper

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

1 个答案:

答案 0 :(得分:0)

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