如果我在 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; }
}
List<Category>從 Book 實體中獲取 a 的最佳做法是什么?在 EF6 中,我只能查詢Book.Categories
uj5u.com熱心網友回復:
如果您使用的是 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 Framework 的最后一個版本,因此您可能會被它困住 - 您需要包含兩個級別的導航屬性,然后從中選擇類別串列:
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();
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/416599.html
標籤:
