代码之家  ›  专栏  ›  技术社区  ›  AllocSystems

查询多对多关系

  •  0
  • AllocSystems  · 技术社区  · 7 年前

    我在官方网站上看到了关于人际关系的帖子asp.net核心文件: asp.net core model relationships

    public class Post
    {
        public int PostId { get; set; }
        public string Title { get; set; }
        public string Content { get; set; }
    
        public List<PostTag> PostTags { get; set; }
    }
    
    public class Tag
    {
        public string TagId { get; set; }
    
        public List<PostTag> PostTags { get; set; }
    }
    
    public class PostTag
    {
        public int PostId { get; set; }
        public Post Post { get; set; }
    
        public string TagId { get; set; }
        public Tag Tag { get; set; }
    }
    

    如果我想返回所有标签的列表,我会这样做:

    public async Task<IEnumerable<Tag>> AllTags()
    {
    return await _context.Tags
    .Include(q => q.PostTags).ThenInclude(q => q.Post);
    }
    

    我如何才能返回标签和他们申请的职位数量?

    预算(3)

    1 回复  |  直到 7 年前
        1
  •  2
  •   Shyju    7 年前

    首先创建一个视图模型类来表示要传递的数据

    public class PostCount
    {
        public string Name { get; set; }
        public int Count { get; set; }
    }
    

    现在在action方法中,可以查询 Tags 集合并呼叫 Count PostTags 各自的财产 Tag 对象。在LINQ表达式中,可以进行投影来创建视图模型对象。

    public async Task<IEnumerable<PostCount>> AllTags()
    {
        var tags = await _context.Tags
                                 .Select(a => new PostCount
                                              {
                                                 Name = a.Name,
                                                 Count = a.PostTags.Count()
                                              }
                                        ).ToListAsync();
    
        return tags;
    }
    

    当您访问此操作方法时,上面的命令将返回所需的数据。

    如果您在视图中显示这个,您可以将我们创建的列表返回到您的视图中。在您的视图中,它是强类型的 PostCount 类,可以呈现标记名及其post count

    public async Task<IEnumerable<PostCount>> AllTags()
    {
        var tags = await _context.Tags.Select(a => new PostCount
        {
            Name = a.Name,
            Count = a.PostTags.Count()
        }).ToListAsync();
    
        return View(tags);
    }
    

    在你的 AllTags.cshtml

    @model List<PostCount>
    <h3>Tags</h3>
    @foreach(var tag in Model)
    {
      <p>@tag.Name  @tag.Count </p>
    }
    

    另外,您可能需要在 PostTag

    public class PostTag
    {
       public int Id  { set;get; }
       // other properties you have
    }
    
    推荐文章