问题
So I have 2 objects,AlbumDto and AlbumMediaDto.
public class AlbumDto
{
public int AlbumId { get; set; }
public string Title { get; set; }
public DateTimeOffset? AlbumDate { get; set; }
public AlbumMediasDto Media { get; set; }// list of media
}
And I have a method from the repo that would return a list of albums (where each has the properties mentioned above which includes a list of media)
var albumsForChild = await GetTenantRepository<IAlbumRepository>().GetAlbumsForChild(childId);
So I'm not sure how to map them to these Dtos using the AutoMapper ( I know that I can always use a nested foreach and fill everything accordingly but thought of learning how to do this the right way).
Any help appreciated!
回答1:
Can you work with JSon deserialization? If yes, below can be your solution.
Business logic:
public IEnumerable<AlbumDto> GetAllAlbums()
{
var allAlbums = _theApiWrapper.ExecuteGet<IEnumerable<AlbumDto>>("theApiRoute");
return allAlbums;
}
Repository:
public T ExecuteGet<T>(string endpoint)
{
var uri = $"https://apiurl.company.com/api/v1/{endpoint}";
using (HttpClient client = new HttpClient())
{
var x = client.GetAsync(uri);
var result = x.Result.Content.ReadAsStringAsync().Result;
return JsonConvert.DeserializeObject<T>(
result,
new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }
);
}
}
来源:https://stackoverflow.com/questions/53104181/nested-lists-and-automapper-map