Automapper: map child property with existing mapper using instance API

家住魔仙堡 提交于 2019-12-02 20:33:01

问题


I'm trying to map one complex object to another using instance API:

 var config = new MapperConfiguration(cfg =>
        {
            cfg.CreateMap<Student, PersonType>();
            cfg.CreateMap<Professor, PersonType>();

            cfg.CreateMap<Branch, BranchType>()
                .ForMember(x => x.Departments, opt => opt.MapFrom(src =>
                    new DepartmentType[] {
                        new DepartmentType
                        {
                            Students = Mapper.Map<Student[], PersonType[]> (src.Students),
                            Professors = Mapper.Map<Professor[], PersonType[]> (src.Professors),
                            Name = src.DepartmentName
                        }
                    }))
                .ForMember(x => x.Name, opt => opt.MapFrom(src => src.Name))
                .ForAllMembers(opts => opts.Condition((src, dest, srcMember) => srcMember != null));
        });

var mapper = config.CreateMapper();
var test = mapper.Map<BranchType>(source);

The problem is I don't know how to achieve this without mixing instance and static API which is not working. Here is the error:

InvalidOperationException: Mapper not initialized. Call Initialize with appropriate configuration. If you are trying to use mapper instances through a container or otherwise, make sure you do not have any calls to the static Mapper.Map methods, and if you're using ProjectTo or UseAsDataSource extension methods, make sure you pass in the appropriate IConfigurationProvider instance.

Apparently mixing of the static and instance based approaches is not allowed:

Students = Mapper.Map<Student[], PersonType[]> (src.Students)

How to use existing map to apply it to a property of the complex object with instance API?

来源:https://stackoverflow.com/questions/57345813/automapper-map-child-property-with-existing-mapper-using-instance-api

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