【问题标题】:Nested Lists and Automapper.Map嵌套列表和 Automapper.Map
【发布时间】:2018-11-01 15:18:49
【问题描述】:

所以我有 2 个对象,AlbumDto 和 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
}

我有一个来自 repo 的方法,它会返回一个专辑列表(其中每个都有上面提到的属性,其中包括一个媒体列表)

var albumsForChild = await GetTenantRepository<IAlbumRepository>().GetAlbumsForChild(childId);

所以我不确定如何使用 AutoMapper 将它们映射到这些 Dto(我知道我总是可以使用嵌套的 foreach 并相应地填充所有内容,但我想学习如何以正确的方式做到这一点)。

任何帮助表示赞赏!

【问题讨论】:

  • 文档不够吗? (Lists, nested mapping)。
  • @KennethK。我在不同的文件中有配置,您是否暗示将其添加到我的配置文件( cfg.CreateMap(); cfg.CreateMap();)并使用 albumsDto = Mapper.Map >(专辑);应该够了吧?它会自动链接内部列表吗?
  • 只要 AlbumsDto 是 IEnumerable 类型,上面的配置应该可以工作

标签: c# asp.net-web-api automapper dto


【解决方案1】:

您可以使用 JSON 反序列化吗?如果是,以下可以是您的解决方案。

业务逻辑:

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

【讨论】:

  • 这不适用于我的基础架构,但听起来像是一个解决方案。
猜你喜欢
  • 2011-08-15
  • 1970-01-01
  • 2019-08-07
  • 2016-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多