ASP .Net Core: Many-to-Many relationship Get operation

I have 2 entities connected by a many to many relationship.

First class:

 public class Movie  {      public int Id { get; set; }      public string Title { get; set; }       public List<MovieActor> MovieActor { get; set; }  } 

Second class:

 public class Actor  {      public int Id { get; set; }      public string Name { get; set; }       public List<MovieActor> MovieActor { get; set; }  } 

And relationship (many to many):

public class MovieActor  {      public int MovieId { get; set; }      public Movie Movie { get; set; }       public int ActorId { get; set; }      public Actor Actor { get; set; }  } 

I want to write the IEnumerable<Movie> GetMovies(int actorId) method, which takes the actor’s id as the parameter. I would like the method to return a list of movies in which an actor with the given Id plays. How can i do that?

Add Comment
2 Answer(s)

You do not need the MovieActor class

Change to:

public class Movie  {      public int Id { get; set; }      public string Title { get; set; }       public List<Actor> Actors { get; set; }  }   public class Actor  {      public int Id { get; set; }      public string Name { get; set; }       public List<Movie> Movies { get; set; }  } 

Then you can select the Actor and you have the list of Movies as a property on the actor.

Answered on July 16, 2020.
Add Comment

so you can do something like this

 public IEnumerable<Movie> GetMovies(int actorId)  {      var result = await _context.Actor.Where(x => x.Id == actorId).                                           Include(x => x.MovieActor).ThenInclude(x => x.Movie).FirstOrDefaultAsync();               var movies = result.MovieActor.select(x => x.Movie).Tolist();      return movies   } 
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.