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

时间:2014-11-06 12:30:15

标签: c# asp.net entity-framework

我在该实体中有一个TheaterMovieShowTime实体我希望通过对特定列进行分组来获取行计数,比如说TheaterMovieDetailID。

这是我的实体:

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

这是我的TheaterMovieDetail实体:

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分组的行。

感谢您提供的任何帮助。如果您需要任何其他信息来帮助回答此问题,请与我们联系

1 个答案:

答案 0 :(得分:1)

使用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
    });