Nested Lists and Automapper.Map

和自甴很熟 提交于 2019-12-11 12:15:57

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!