Reputation: 241
I have two external endpoints, which results I need to merge into one single DTO object. I am lost at some point as I am trying to figure out a way, how I can inject a collection of albums when only there is a match between Album UserId and UserDetailDTO Id.
Endpoint 1 - https://jsonplaceholder.typicode.com/users
Endpoint 2 - https://jsonplaceholder.typicode.com/albums
Below you can find my classes:
public class UserDetailDTO
{
public int Id { get; set; }
public string Name { get; set; }
public string Username { get; set; }
public List<Album> Albums { get; set; }
}
public class User
{
[JsonProperty("id", NullValueHandling = NullValueHandling.Ignore)]
public int Id { get; set; }
[JsonProperty("name", NullValueHandling = NullValueHandling.Ignore)]
public string Name { get; set; }
[JsonProperty("username", NullValueHandling = NullValueHandling.Ignore)]
public string Username { get; set; }
}
public class Album
{
[JsonProperty("userId", NullValueHandling = NullValueHandling.Ignore)]
public int UserId { get; set; }
[JsonProperty("id", NullValueHandling = NullValueHandling.Ignore)]
public int Id { get; set; }
[JsonProperty("title", NullValueHandling = NullValueHandling.Ignore)]
public string Title { get; set; }
}
public MappingProfile()
{
var userMap = CreateMap<User, UserDetailDTO>();
var albumMap = CreateMap<Album, UserDetailDTO>();
}
In the service part, I am able to get the json results from these endpoints but I am failing at the AutoMapper part.
var users = JsonConvert.DeserializeObject<List<User>>(usersResponseContent);
var albums = JsonConvert.DeserializeObject<List<Album>>(albumsResponseContent);
var mappedUsers = _mapper.Map(albums, _mapper.Map<List<User>, List<UserDetailDTO>>(users));
Upvotes: 0
Views: 1723
Reputation: 1878
Instead of using the mapper for assigning the albums to the DTO, you can do the below thing
var users = JsonConvert.DeserializeObject<List<User>>(usersResponseContent);
var albums = JsonConvert.DeserializeObject<List<Album>>(albumsResponseContent);
var mappedUsers = _mapper.Map<List<User>, List<UserDetailDTO>>(users);
foreach (var user in mappedUsers)
user.Albums = albums.Where(x => x.UserId == user.Id);
Upvotes: 1