自动映射器:使用实例API使用现有映射器映射子属性

时间:2019-08-04 10:32:33

标签: c# .net-core automapper

我正在尝试使用实例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);

问题是我不知道如何在不混合实例和无法正常工作的静态API的情况下实现这一目标。这是错误:

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.

显然不允许将静态方法与基于实例的方法混合使用:

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

如何通过实例API如何使用现有地图将其应用于复杂对象的属性?

0 个答案:

没有答案