2

I have two models in my project. first for Movie and second for Genre. There is a many-to-many relation between the two. So I created another model named MovieGenre. The problem is I don't know how to implement a search function in the controller for name of the Genre. To retrieve a movie with the specified genre name I mean.

Here is the three models

public class Movie
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public List<MovieGenre> MovieGenres { get; set; }
        public string Director { get; set; }
        public DateTime ReleaseDate { get; set; } = DateTime.Now;

    }

public class Genre
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public List<MovieGenre> MovieGenres { get; set; }
    }

public class MovieGenre
    {
        public int MovieId { get; set; }
        public int GenreId { get; set; }
        public Movie Movie { get; set; }
        public Genre Genre { get; set; }
    }
ahamad zooghi
  • 67
  • 1
  • 8
  • Does this answer your question? [Filtering on Include in EF Core](https://stackoverflow.com/questions/43618096/filtering-on-include-in-ef-core) – burnsi Mar 04 '22 at 09:56
  • 1
    I don't understand why you don't just create a List prop in Genre model, no need for MovieGenre model – big boy Mar 04 '22 at 09:58

1 Answers1

3

This query has nothing with Include but how to implement filter

var result = ctx.Movie
    .Where(m => m.MovieGenres.Any(mg => mg.Genre.Name == genreName))
    .ToList();

If you are using EF Core 5+, consider to simplify your model. Intermediate entity can be omitted/hidden, check documentation:

public class Movie
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<Genre> Genres { get; set; }
    public string Director { get; set; }
    public DateTime ReleaseDate { get; set; } = DateTime.Now;
}

public class Genre
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<Movie> Movies { get; set; }
}
var result = ctx.Movie
    .Where(m => m.Genres.Any(g => g.Name == genreName))
    .ToList();
Svyatoslav Danyliv
  • 21,911
  • 3
  • 16
  • 32