Search code examples
c#.net-coregetasp.net-core-webapiicollection

.Net Core Web Api / HttpGet / About Get ICollection


Firstly, sorry for my English, it is not perfect. I hope i can explain my problem.

WebApi has Movie Class like this

    public class Movie
    {
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }
        public string Name { get; set; }
        public DateTime ReleaseDate { get; set; }
        public float Price { get; set; }
        public int DirectorID { get; set; }
        public Director Director { get; set; }
        public int GenreID { get; set; }
        public Genre Genre { get; set; }
        public ICollection<Actor> Actors { get; set; }
    }

When I used HttpGet Movies it happens

It cant read actors. How can i fix this?

GetMoviesQuery

namespace WebApi.Application.MovieOperations.Queries.GetMovies
{
    public class GetMoviesQuery
    {
        private readonly IMovieStoreDbContext _context;
        private readonly IMapper _mapper;
        public GetMoviesQuery(IMovieStoreDbContext context, IMapper mapper)
        {
            _context = context;
            _mapper = mapper;
        }

        public List<GetMoviesModel> Handle()
        {
            var _movieList = _context.Movies.Include(x => x.Genre).Include(y => y.Director).OrderBy(z => z.Id).ToList<Movie>();
            List<GetMoviesModel> mv = _mapper.Map<List<GetMoviesModel>>(_movieList);
            return mv;
        }
    }
    public class GetMoviesModel
    {
        public string Name { get; set; }
        public string ReleaseDate { get; set; }
        public string Genre { get; set; }
        public string Director { get; set; }
        public float Price { get; set; }
        public ICollection<Actor> Actors { get; set; }
    }
}

Thank you.


Solution

  • you have to include actors too

    var _movieList = _context.Movies
                       .Include(x => x.Actors)
                        .Include(x => x.Genre)
                         .Include(y => y.Director)
                          .OrderBy(z => z.Id)
                          .ToList();
    

    UPDATE:

    If you only need the First and the last names of actors you will have to create a model class

    public class ActorViewModel
    {
     public string Name { get; set; }
     public string SurName { get; set; }
    }
    

    and fix GetMoviesModel accordingly

     public class GetMoviesModel
        {
            public string Name { get; set; }
           .....
            public ICollection<ActorViewModel> Actors { get; set; }
        }