【问题标题】:.Net Core Web Api / HttpGet / About Get ICollection.Net Core Web Api / HttpGet / 关于获取ICollection
【发布时间】:2021-11-08 17:49:35
【问题描述】:

首先,对不起我的英语,它并不完美。我希望我能解释我的问题。

WebApi 有这样的电影类

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

当我使用 HttpGet 电影时 it happens

它无法读取演员。我该如何解决这个问题?

获取电影查询

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

谢谢。

【问题讨论】:

    标签: c# .net-core get asp.net-core-webapi icollection


    【解决方案1】:

    你也必须包括演员

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

    更新:

    如果您只需要演员的名字和姓氏,则必须创建一个模型类

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

    并相应地修复 GetMoviesModel

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

    【讨论】:

    • 谢谢。如何只显示演员姓名和演员姓氏?当我这样做时,它显示了演员的所有属性。有过滤选项吗?
    • @Oguzhan 欢迎您。请检查我的答案更新
    猜你喜欢
    • 2021-10-28
    • 2020-06-14
    • 2021-12-16
    • 2018-12-20
    • 2021-10-18
    • 2018-05-08
    • 2020-11-23
    • 2019-12-17
    • 1970-01-01
    相关资源
    最近更新 更多