Search code examples
c#entity-framework-6many-to-many

EF 6 fetch results with many-to-many relations in c#


Need to fetch linked table data in C#, here is the case

public class Book
{
    public int BookId { get; set; }
    public string Title { get; set; }
    public virtual ICollection<BookCategory> BookCategories { get; set; }
}

public class Category
{
    public int CategoryId { get; set; }
    public string CategoryName { get; set; }
    public virtual ICollection<BookCategory> BookCategories { get; set; }
}

public class BookCategory
{
    [Key, Column(Order = 1)]
    public int BookId { get; set; }
    [Key, Column(Order = 2)]
    public int CategoryId { get; set; }
    public Book Book { get; set; }
    public Category Category { get; set; }
}

Now I need to fetch a List of books with BooksCategories for each book from DB in a single Linq Query with EF 6. Specifically, I need the BookCategories property to be filled up for each Book in the list of Books with the best code.

Can you please suggest the C# code for the same?


Solution

  • You can load related entities with Include. So your LINQ should look something like this

    using (var context = new EntityContext())
    {
        var books = context.Books
           .Include(b => b.BookCategories)
           .ToList();
    }
    

    You can read more about here