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

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

bozipk 回答:按照约定从Collection <T>映射到Collection <T>

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

本文链接:https://www.f2er.com/3143479.html

大家都在问