本文介绍了从集合< T>映射收集到< T>按照惯例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以从类型为Collection< T>的属性进行映射到类型为Collection< T>的另一个属性按照惯例,无需显式定义映射?

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

当我取消注释ForMember(..)时,此方法有效.我是否缺少基于约定的方法的东西?

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

推荐答案

您需要使用setter或MapFrom(以您喜欢的为准):)在10之前的版本中就是这种情况.版本10中的行为.

You need either a setter, or the MapFrom, whichever you prefer :) That's the case in versions before 10. Check the link in the comment for the behavior in version 10.

这篇关于从集合&lt; T&gt;映射收集到&lt; T&gt;按照惯例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 08:35