简体   繁体   English

实体框架多对多关系查询

[英]Entity framework many to many relations query

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.我被困在 function 上,我想在其中显示某个类别的所有书籍。 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!我知道它在胡同里的某个地方。Include() function 但我走到了死胡同,需要一些指针来解决这个问题 - 谢谢!

This is how my models look like:这就是我的模型的样子:

Models/book.cs模型/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模型/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.这应该可行,尽管我现在更习惯于实体框架核心。

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

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