I'm working on a project where I have two models that are related too each other. Books and BookCategories. I'm stuck on a function where I want to show all books that are in a certain category. Like, display all books in the category "Horror". I know its in the alley somewhere with the.Include() function but I hit a dead end and would need some pointers to figure this out - Thank you!
This is how my models look like:
Models/book.cs
class Book
{
[Key]
public int Id { get; set; }
public string Title { get; set; }
public string Author { get; set; }
public int Price { get; set; }
public int Amount { get; set; }
public List<BookCategory> BookCategories { get; set; }
}
Models/BookCategory.cs
class BookCategory
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public List<Book> Books { get; set; }
}
I know so far I can include the category with the books
db.Books.Include("BookCategory");
But I don't know how to match the criteria to tell I only want to get the books with a certain category
If you want to filter by categories you can do something like this:
db.Books
.Include("BookCategory")
.Where(b => b.BookCategories.Any(c=>c.Name == "Horror"));
That should work, although I'm more accustomed to entity framework core now.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.