简体   繁体   English

如何使用LINQ从表中选择存在于联结表中的元素-Entity Framework

[英]How to select elements from a table that are present in a junction table with LINQ - Entity Framework

I have 3 tables: 我有3张桌子:

  • Book : id - title - etc 书:id-标题-等等
  • BookInstance : id - column - row - etc BookInstance:id-列-行-等等
  • BookBookInstance (junction) bookId - bookInstanceId - Id BookBookInstance(交界处)bookId-bookInstanceId-ID

I want to retrieve the bookinstances for a book and i get a book ID as a parameter. 我想检索一本书的bookinstances,然后获取书ID作为参数。 How do i do that? 我怎么做? I'm working on an ASP.NET MVC 5 project i can either use LINQ or anything given by C#, but i would love to see the SQL query as well so i can learn :) 我正在开发一个ASP.NET MVC 5项目,我可以使用LINQ或C#提供的任何东西,但是我也希望看到SQL查询,因此我可以学习:)

public List<BookInstance> GetBookInstancesForBook(string bookId)
    {
        using (var db = new LibraryDataContext())
        {
            // Any solutions?         
        }
    }

You can do something like : 您可以执行以下操作:

var bookInstances = db.BookBookInstance.Where(x => x.BookId == bookId)
                      .Select(x => x.BookInstance).ToList();

Is this what you are looking for? 这是你想要的? (may need some tweaking since I dont have your entity models - the include may need to be singular depending on the object model) (由于我没有您的实体模型,可能需要进行一些调整-根据对象模型的不同,include可能需要为单数)

public List<BookInstance> GetBookInstancesForBook(string bookId)
{
    using (var db = new LibraryDataContext())
    {
        var results = (from b in db.Books
            .include("BookBookInstances")
        where b.ID == bookID
        select b.BookInstances        
       ).ToList();
    }
}

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

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