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 自動處理。
- 1 回答
- 0 關注
- 159 瀏覽
添加回答
舉報