嵌套列表和Automapper.Map [英] Nested Lists and Automapper.Map

查看:92
本文介绍了嵌套列表和Automapper.Map的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有2个对象,AlbumDto和AlbumMediaDto.

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);

因此,我不确定如何使用AutoMapper将它们映射到这些Dto(我知道我总是可以使用嵌套的foreach并相应地填充所有内容,但是想学习如何正确地进行此操作).

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).

任何帮助表示赞赏!

推荐答案

您可以使用JSon反序列化吗?如果是的话,下面是您的解决方案.

Can you work with JSon deserialization? If yes, below can be your solution.

业务逻辑:

public IEnumerable<AlbumDto> GetAllAlbums()
{
    var allAlbums = _theApiWrapper.ExecuteGet<IEnumerable<AlbumDto>>("theApiRoute");
    return allAlbums;
}

存储库:

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 }
            );
    }
}

这篇关于嵌套列表和Automapper.Map的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆