Search code examples
c#linqautomapper

Using Automapper in C# to create a View for multiple child nested objects


I am trying to implement EFCore and Automapper into a project, and I am struggling a bit to get some properties correctly queried. Below, I will show you what my objects look like:

public class Request {
  public int RequestID { get; set; }
  ...
  ...
  ...
  public virtual ICollection<RequestApplication> RequestApplications { get; set; }
}

public class RequestApplication {
  ...
  public virtual Application Application { get; set; }
}

public class Application {
  public string Name { get; set; }
}

public class ManagedRequestsDTO {
  public int RequestID { get; set; }
  ...
  ...
  public string Systems { get; set; }
}

I am attempting to use AutoMapper and it's custom mappings to map my properties over to my DTO. The one property I am struggling with is Systems, which is basically the string concatenation of my Application.Name. With the below data:

{
  "RequestID": "5",
  "RequestApplications": [
    {
      "Application": {
        "Name": "Apple"
      }
    },
    {
      "Application": {
        "Name": "Pear"
      }
    }
  ]
}

...I want my DTO object to store the System value as "Apple Pear". Is there a nice and easy way of doing that with the AutoMapper right now? I'll example the AutoMapper that I have now:

CreateMap<Request, ManageRequestDTO>()
  .ForMember(dest => dest.RequestID, opt => opt.MapFrom(src => src.RequestID);

Solution

  • This should work to map the JSON example you provided:

      CreateMap<Request, ManageRequestDTO>()
          .ForMember(dest => dest.Systems, opt => opt.MapFrom(src => 
               string.Join(' ', src.RequestApplications.Select(ra => ra.Application.Name));
    

    Note that RequestApplication.Application is an ICollection<Application> in your model class but that does not match the JSON example, ie, :

        # Not a collection!
        "Application": {
            "Name": "Apple"
          }.