为了账号安全,请及时绑定邮箱和手机立即绑定

自动映射数组类

自动映射数组类

C#
qq_遁去的一_1 2023-09-24 16:23:25
我有一个目标对象ArrayOfStudents[]含有StudentId,    AddressInfo,    MarksInfo源对象是public class Details{    public Student[] Student;)学生类包含学生号、地址信息、标记信息我想要地图Student[]和ArrayOfStudents[]我尝试了以下方法,但没有成功Map.CreateMap<Student,ArrayOfStudents>() .ReverseMap(); Map.CreateMap<Details.Student,ArrayOfStudents>() .ReverseMap();我应该如何绘制这个案例?它抛出以下未映射错误学生号、地址信息、标记信息
查看完整描述

1 回答

?
有只小跳蛙

TA贡献1824条经验 获得超8个赞

使用 Automapper,您可以将一种类型映射到另一种类型。当您这样做时,将自动映射相同类型的数组。


ArrayOfStudents在您的情况下,您将创建和之间的地图Student。这将是一个简单的映射,因为两个映射类型之间的类型和名称是相同的:


public class MappingProfile : Profile

{

    public MappingProfile()

    {

        this.CreateMap<Student, ArrayOfStudents>();


        this.CreateMap<ArrayOfStudents, Student>();

    }

}

现在,无论您打算在哪里进行实际映射(例如 RESTful 控制器),您都可以执行以下操作:


public class MyController

{

    private readonly IMapper mapper;


    public MyController(IMapper mapper)

    {

        this.mapper = mapper;

    }


    // Then in any of your methods:

    [HttpGet]

    public IActionResult MyMethod()

    {

        var objectsToMap = details.Student; // This is an array of Student type.

        var mappedObjects = this.mapper.Map(objectsToMap); // This will be an array of ArrayOfStudents.

        // do what you will with the mapped objects.

    }

}

想法是,您注册类型的映射(包括类型中成员的类型)。然后,这些类型的集合的映射由 Automapper 自动处理。


查看完整回答
反对 回复 2023-09-24
  • 1 回答
  • 0 关注
  • 76 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信