Home > Enterprise >  How to get a list of objects that contain another list of objects in EF6
How to get a list of objects that contain another list of objects in EF6

Time:10-14

I have 2 entities:

  • Books;
  • Genres;

They have a many-to-many relationship:

public class Book
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<Genre> Genres { get; set; }
}

public class Genre
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<Book> Books { get; set; }
}

The task is to implement a search by genre.

Using a list/array of genre IDs, find all books that contain all the genres in the array. The result may include books containing other genres, but they must have the requested ones.

Using something like this:

var genres = _db.Genres.Where(g => genresIdList.Contains(g.Id)).ToList();
var books = _db.Books.Where(b => genres.All(b.Genres.Contains));

Leads to an exception.

CodePudding user response:

Use the following query:

var books = _db.Books.Where(b => b.Genres.Any(g => genresIdList.Contains(g.Id)));

CodePudding user response:

The solution to my problem was:

var genres = _db.Genres.Where(g => genresIdList.Contains(g.Id));
var books = books.Where(b => genres.All(genre => b.Genres.Contains(genre)));

After removing Genre's ToList() and changing the LINQ query a little, the exception disappeared.

Thanks to everyone who tried to help :)

  • Related