简体   繁体   English

Linq外键| 如何仅显示具有特定外键的元素?

[英]Linq Foreign Key | How to display only the elements with a specific foreign key?

I have two tables: Book and Chapter 我有两个表:书和章

Book
ID
Title
Author

Chapter
ChapterID
BookID
Title

I have a method in the Controller which is supposed to display a list of all the Chapters of a Book. 我在Controller中有一个方法,该方法应该显示一本书所有章节的列表。 However, it displays all the elements in the Chapter table, instead of the ones that match the BookID 但是,它将显示“章节”表中的所有元素,而不是与BookID相匹配的元素

Here is my method: 这是我的方法:

public ActionResult ViewChapters()
    {
        var chapters = db.Chapters
                             .Where(x => x.BookId ==  x.Book.ID)
                             .Include(x => x.Book).ToList();
        return View(chapters);
    }

I guess it's something wrong with my linq query. 我想我的linq查询有问题。

You should pass the id of the book to the method, otherwise there's no way the code knows which book you're referencing. 您应该将书的ID传递给方法,否则代码将无法知道您要引用的书。

public ActionResult ViewChapters(Guid bookId)
{
    var chapters = db.Chapters
                         .Where(x => x.BookId == bookId)
                         .Include(x => x.Book).ToList();
    return View(chapters);
}

The Where predicate evaluates each item in db.Chapters and only keeps the items where the predicate returns true. Where谓词评估db.Chapters每个项目,并且仅保留谓词返回true的项目。 As Fabio mentions in the comments, when you compare x.BookId == x.Book.ID , the result is true for each item in the db.Chapters collection. 正如Fabio在评论中提到的那样,当您比较x.BookId == x.Book.ID ,对于db.Chapters集合中的每个项目,结果均为true。

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

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