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

爷,独闯天下 提交于 2020-01-25 07:23:15

问题


Is it possible to map from a property of type Collection<T> to another property of type Collection<T> by convention without the need to define the mapping explicitly?

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>();
    }
}

When I uncomment the ForMember(..) this works. Am I missing something for the convention based method?


回答1:


You need either a setter, or the MapFrom, whichever you prefer :)



来源:https://stackoverflow.com/questions/58752261/mapping-from-collectiont-to-collectiont-by-convention

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!