简体   繁体   中英

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

I have 3 tables:

  • Book : id - title - etc
  • BookInstance : id - column - row - etc
  • BookBookInstance (junction) bookId - bookInstanceId - Id

I want to retrieve the bookinstances for a book and i get a book ID as a parameter. 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 :)

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)

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();
    }
}

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.

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