如何连同相关标签一起返回文章

时间:2018-09-11 10:56:52

标签: c# asp.net-web-api asp.net-core

我有三个表:Articles,Tags和ArticleTag。 Article模型与将ArticleTag作为联合的Tag模型具有多对多关系。 这些是模型:

public class Article
{
    ... 

    public ICollection<ArticleTag> ArticleTags { get; set; }
}

public class Tag
{
    ... 

    public ICollection<ArticleTag> ArticleTags { get; set; }
}

public class ArticleTag
{
    public int ArticleId { get; set; }
    public Article Article { get; set; }

    public int TagId { get; set; }
    public Tag Tag { get; set; }
}

这是如何获得这篇文章:

public Article GetArticleById(int id)
{
    return _appContext.Articles
        .Include(a => a.ArticleTags).ThenInclude(at => at.Tag)
        .FirstOrDefault(a => a.Id == id);
}

视图模型:

public class ArticleViewModel
{
    ...

    public ICollection<TagViewModel> Tags { get; set; }
}

这是控制器:

[HttpGet("{id:int}")]
public IActionResult Get(int id)
{
    var article = _unitOfWork.Articles.GetArticleById(id);

    return Ok(Mapper.Map<ArticleViewModel>(article));
}

API请求返回文章,但不包含标签。

1 个答案:

答案 0 :(得分:1)

请尝试下面的代码来配置Mapper

  1. TagViewModel

    public class TagViewModel
    {
        public int Id { get; set; }
        public string TagName { get; set; }
    
    }
    
  2. AutoMapperProfile

    public class AutoMapperProfile : Profile
    {
       public AutoMapperProfile()
       {
          CreateMap<Article, ArticleViewModel>()
              .ForMember(dest => dest.Tags, opt => opt.MapFrom(src => src.ArticleTags.Select(at => at.Tag)));
          CreateMap<Tag, TagViewModel>();
       }
    }