查询多对多ef核心关系

时间:2020-07-06 12:42:58

标签: ef-core-3.1

我有以下课程

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

我不确定如何获取给定Book的所有Category。我正在使用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();

1 个答案:

答案 0 :(得分:1)

由于性能原因,不建议使用.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;

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