I'm working in a project that uses AutoMapper to map from our ORM (Object-Relational Mapper) POCOs (Plain Old CLR Objects) to the view models we present to the UI.
I have an instance in which doing so involves aggregating records.
The POCO that is our input:
public class WorkRecord
{
public int id {get; set; }
public string work { get; set; }
public string type { get; set; }
public string result { get; set; }
}
And what we want as an output:
public class WorkViewModel
{
public string Work { get; set; }
public List<WorkInstance> WorkInstances { get; set; }
public class WorkInstance
{
public string Type { get; set; }
public string Result { get; set; }
}
}
What I want is to convert a list of WorkRecords into a list of WorkViewModels, where the number of WorkViewModels output is not the same as the number of WorkRecords.
I want one WorkViewModel for each distinct WorkRecord.work, with a child WorkViewModel.WorkInstance created for each WorkRecord with that WorkRecord.work.
E.g.:
[
{id: 1, work: "WorkA", type: "Type1", result: "Success"},
{id: 2, work: "WorkA", type: "Type2", result: "Failure"},
{id: 3, work: "WorkB", type: "Type3", result: "Success"},
{id: 4, work: "WorkB", type: "Type4", result: "Failure"},
]
Should result in:
[
{
Work: "WorkA",
WorkInstances: [
WorkInstance: {
Type: "Type1",
Result: "Success"
},
WorkInstance: {
Type: "Type2",
Result: "Failure"
}
]
},
{
Work: "WorkB",
WorkInstances: [
WorkInstance: {
Type: "Type3",
Result: "Success"
},
WorkInstance: {
Type: "Type4",
Result: "Failure"
}
]
}
]
I'm not seeing a great way of doing this in AutoMapper.
Any ideas?
Edited to fix syntax on WorkInstance declaration.
What I've not been about to figure out is how to map a collection of n input objects to m output objects, where m < n.