我的班级看起来像这样:

public class Student{
    public string Name { get; set; }
    public string Id { get; set; }
    public List<Course> Courses { get; set; }
    public string Address { get; set; }
}

public class Course{
    public string Id { get; set; }
    public string Description { get; set; }
    public Date Hour { get; set; }
}


我想使用AutoMapper将Student类映射到以下类

public class StudentModel{
    public string Id { get; set; }
    public StudentProperties Properties { get; set; }
}


其中StudentProperties是学生类的其余属性

public class StudentProperties{
    public string Name { get; set; }
    public List<Course> Courses { get; set; }
    public string Address { get; set; }
}


基于AutoMapper文档(https://github.com/AutoMapper/AutoMapper/wiki),我们可以在执行映射时使用自定义解析器来解析目标成员。
但是我不想为解析器添加新类。

我想知道是否存在通过执行以下简单配置来执行映射的简单方法:

Mapper.Initialize(cfg =>
{
    cfg.CreateMap<Student, StudentProperties>();
    cfg.CreateMap<Student, StudentModel>();
});

最佳答案

这是一个对您有用的选项,并且对AutoMapperStudentModel使用StudentProperties

Mapper.Initialize(cfg =>
{
    cfg.CreateMap<Student, StudentProperties>();
    cfg.CreateMap<Student, StudentModel>()
        .ForMember(dest => dest.Properties,
            opt => opt.ResolveUsing(Mapper.Map<StudentProperties>));
});


在这里,我们使用ResolveUsing,但是使用Func<>版本以避免创建新类。该Func<>本身就是Mapper.Map,它已经知道如何从Student映射到StudentProperties

关于c# - 使用AutoMapper映射对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46675440/

10-12 16:35
查看更多