使用entityframework中的group by获取行计数

本文关键字:获取 by entityframework 中的 group 使用 | 更新日期: 2023-09-27 18:29:19

我在该实体中有一个TheaterMovieShowTime实体,我想通过对特定列(例如TheaterMovie DetailID)进行分组来获得行计数。

这是我的实体:

public class TheaterMovieShowTime
{
   public int TheaterMovieShowTimeID { get; set; }
   public int TheaterMovieDetailID { get; set; }
    public int TheaterShowTimeID { get; set; }
    public virtual TheaterMovieDetail TheaterMovieDetails { get; set; }
    public virtual TheaterShowTime TheaterShowTime { get; set; }
}

这是我的影院电影细节实体:

public class TheaterMovieDetail
{
    public int TheaterMovieDetailID { get; set; }
    public int TheaterID { get; set; }
    public int MovieID { get; set; }
    public DateTime DateFrom { get; set; }
    public DateTime DateTo { get; set; }
    public virtual Movie Movie { get; set; }
    public virtual Theater Theater { get; set; }
    public virtual ICollection<TheaterMovieShowTime> TheaterMovieShowTimes { get; set; }
}

我试试这个:

 var p = _theaterMovieShowTimeService.GetAllTheaterMovieShowTime()
            .GroupBy(x => x.TheaterMovieDetailID)
            .Select(x => new TheaterMovieShowTimeSummaryViewModel
            {
                TheaterName = x.FirstOrDefault().TheaterMovieDetails.Theater.TheaterName,
                MovieName = x.FirstOrDefault().TheaterMovieDetails.Movie.MovieName,
                NoOfShows=???????? // get the no of rows here
            });

如何在此处获得NoOfShows,即按TheaterMovieDetailID分组的行数。

如果有任何帮助,我将不胜感激。如果您需要任何其他信息来帮助回答这个问题,请告诉我

使用entityframework中的group by获取行计数

使用linq Count()函数:

var p = _theaterMovieShowTimeService.GetAllTheaterMovieShowTime()
    .GroupBy(x => x.TheaterMovieDetailID)
    .Select(x => new TheaterMovieShowTimeSummaryViewModel
    {
        TheaterName = x.FirstOrDefault().TheaterMovieDetails.Theater.TheaterName,
        MovieName = x.FirstOrDefault().TheaterMovieDetails.Movie.MovieName,
        NoOfShows= x.Count()  // get the no of rows here
    });