Home > OS >  How to implement searching with Include in ASP.NET CORE
How to implement searching with Include in ASP.NET CORE

Time:03-05

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

CodePudding user response:

This query has nothing with Include but how 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();
  • Related