【问题标题】:How to implement many to many relationship in ASP.NET CORE WEB API如何在 ASP.NET CORE WEB API 中实现多对多关系
【发布时间】:2020-11-26 21:12:25
【问题描述】:

所以我有 4 个班级:

    public class Book
    {
      public int BookId { get; set; }
      public string Title { get; set; }
      public Author Author { get; set; }
      public int AuthorId { get; set; }
      public ICollection<BookCategory> BookCategories { get; set; }
    }  

    public class Author
    {
      public int AuthorId { get; set; }
      public string Name { get; set; }
      public string Surname { get; set; }
      public ICollection<Book> Books { get; set; }
    }  

    public class Category
    {
      public int CategoryId { get; set; }
      public string CategoryName { get; set; }
      public ICollection<BookCategory> BookCategories { get; set; }
    }

    public class BookCategory
    {
      public int BookId { get; set; }
      public Book Book { get; set; }
      public int CategoryId { get; set; }
      public Category Category { get; set; }
    }

我想为 [HttpGet] 请求编写函数,以便它返回如下 JSON:

[
  {
     "bookId": "1",
     "title": "Book Title 1",
     "authorName": "Author Name 1",
     "aurhorSurname": "Author Surname 1",
     "categories": ["category1", "category2"]
  },
  {
     "bookId": "2",
     "title": "Book Title 2",
     "authorName": "Author Name 1",
     "aurhorSurname": "Author Surname 1",
     "categories": ["category2", "category3"]
  },
  {
     "bookId": "3",
     "title": "Book Title 3",
     "authorName": "Author Name 1",
     "aurhorSurname": "Author Surname 1",
     "categories": ["category1", "category4"]
  },
]

我知道如何处理一对多的关系,并且我为作者和书籍创建了 API,其中每个作者都有自己写的一系列书籍。但是这个连接表(BookCategory)让我很困惑。

【问题讨论】:

  • 你有没有尝试过?文档对这些东西有很好的描述:docs.microsoft.com/en-us/ef/core/modeling/…
  • 这里有很多假设:从 dbContext 中获取书籍,包括 BookCategories。映射到视图模型时,只需将类别名称选择到一个数组中,这就是模型所期望的。

标签: c# asp.net .net asp.net-core entity-framework-core


【解决方案1】:

对于返回的json格式,可以先通过Include和ThenInclude获取所有关联数据。

然后使用Select方法和新对象组成返回的数据结构:

        public IActionResult ReturnJson()
        { 
            var data = _context.Book.Include(x => x.Author)
                .Include(x => x.BookCategories).ThenInclude(x => x.Category)
                .Select(x => new
                {
                    bookId = x.BookId,
                    title = x.Title,
                    authorName = x.Author.Name,
                    authorSurname = x.Author.Surname,
                    categories = x.BookCategories.Select(k => k.Category.CategoryName).ToList()
                });
            return Json(data);
        }

这是返回的数据:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-02
    • 2013-08-08
    • 2021-10-29
    • 2016-04-03
    • 1970-01-01
    • 2012-04-05
    • 1970-01-01
    相关资源
    最近更新 更多