繁体   English   中英

EF Core 多对多 linq 查询

[英]EF Core many-to-many linq query

如果我在 EF Core 中有以下类映射多对多关系:

public class Book
{
    public int BookId { get; set; }
    public string Title { get; set; }
    public Author Author { get; set; }
    public ICollection<BookCategory> BookCategories { 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; }
}

从 Book 实例中获取List<Category>的最佳做法是什么? 在 EF6 中,我只能查询Book.Categories

如果您使用的是 EF Core 5.0 或更高版本,则不再需要BookCategory实体。 您可以简单地拥有ICollection<Category> / ICollection<Book> ,就像使用 Entity Framework 6 所做的那样。

public class Book
{
    public int BookId { get; set; }
    public string Title { get; set; }
    public Author Author { get; set; }
    public ICollection<Category> Categories { get; set; }
}  
public class Category
{
    public int CategoryId { get; set; }
    public string CategoryName { get; set; }
    public ICollection<Book> Books { get; set; }
}  

对于 EF Core 3.1 或更早版本 - 这是支持 .NET 框架的最后一个版本,所以你可能会被它困住 - 你需要包括两个级别的导航属性,然后 select 的类别列表:

Book book = await context.Books
    .Include(b => b.BookCategories).ThenInclude(c => c.Category)
    .First(b => b.Id == 42);

List<Category> bookCategories = book.Categories
    .Select(c => c.Category)
    .ToList();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM