查询多对多ef核心关系

Query many-to-many ef core relationship

我关注类

    public class Book
    {
        public string BookId { get; set; }
        public string Title { get; set; } = string.Empty;
        public string Description { get; set; } = string.Empty;

        // Relationships
        public ICollection<BookCategory> CategoriesLink { get; set; }
    }

    public class BookCategory
    {
        public string BookId { get; set; }
        public string CategoryId { get; set; }

        public Book Book { get; set; }
        public Category Category { get; set; }
    }

    public class Category
    {
        public string CategoryId { get; set; }
        public string Name { get; set; }
        public ICollection<BookCategory> BooksLink { get; set; } 
    }

我不确定如何获取给定 Category 的所有 Book。我正在使用 EFCore 3.1。我试过跟随,但不确定是否有效。

    return context.Categories
        .Include(x => x.BooksLink)
        .ThenInclude(x => x.Book)
        .Where(x => x.CategoryId == category)
        .SelectMany(x=>x.BooksLink.Select(y=>y.Book))
        .ToList();

由于性能原因,不建议使用 .Include 方法。

为了更好的查询,我会使用这个 linq

from book in context.book
 join bookCatJoin in context.BookCategory on book.id equals bookCatJoin.BookId
 join category in context.Category.Where(e=>e.Name=="crime") on bookCatJoin.categoryId equals category.CategoryId
 select book;

此查询比包含查询具有更好的性能。因为每个包含都与整个 table 进行左连接。 https://docs.microsoft.com/en-us/ef/core/querying/related-data .Include 的文档突出显示了此建议