1

I would like to ask how I could make a query to select the genre for each book, I tried many ways to do this, but I failed.

Book:

public class Book
{
    public int Id { get; set; }
    [StringLength(100)]
    public string Title { get; set; }
    public virtual ICollection<Genre> Genres { get; set; }
    public virtual Author Author { get; set; }
}

Genre:

public class Genre
{
    public int Id { get; set; }
    [StringLength(32)]
    public string Name { get; set; }
    public virtual ICollection<Book> Books { get; set; }
}

Author:

public class Author
{
    public int Id { get; set; }
    public string FullName { get; set; }
    public virtual ICollection<Book> Books { get; set; }
}

What I tried: (I marked with "?" Where I can no longer do)

from book in Books
join author in Authors on book.Author.Id equals author.Id
??join Genre ??
select new {book, author, ?list genres}
Abdul Cred
  • 13
  • 2
  • https://stackoverflow.com/questions/10505595/linq-many-to-many-relationship-how-to-write-a-correct-where-clause – Thameem May 05 '21 at 14:13

1 Answers1

2

Use SelectMany :

    class Program
    {
         static void Main(string[] args)
        {
            Context db = new Context();

            var results = db.Book.SelectMany(x => x.Genres.Select(y => new
            {
                id = x.Id,
                title = x.Title,
                authorId = x.Author.Id,
                authorName = x.Author.FullName,
                genreId = y.Id,
                genreName = y.Name
            })).ToList();
 

        }
    }
    public class Context
    {
        public List<Book> Book { get; set; }
        public List<Genre> Genre { get; set; }
        public List<Author> Author { get; set; }
    }
    public class Book
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public virtual ICollection<Genre> Genres { get; set; }
        public virtual Author Author { get; set; }
    }
    public class Genre
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public virtual ICollection<Book> Books { get; set; }
    }
    public class Author
    {
        public int Id { get; set; }
        public string FullName { get; set; }
        public virtual ICollection<Book> Books { get; set; }
    }
 
jdweng
  • 33,250
  • 2
  • 15
  • 20