型号类:
public class Video
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime ReleasedDate { get; set; }
public byte GenreId { get; set; }
public Genre Genre { get; set; }
public Classification Classification { get; set; }
public IList<Tag> Tags { get; set; }
}
public class Genre
{
public byte Id { get; set; }
public string Name { get; set; }
public IList<Video> Videos { get; set; }
}
例如,流派名称是:动作,戏剧,喜剧和恐怖。 Comedy and Horror类型没有视频。
查看模型类:
public class CountOfVideos
{
public string Classification { get; set; }
public int NumberOfMovies { get; set; }
}
控制器类:
public ActionResult Movies()
{
var movies = _context.Videos
.GroupBy(v => v.Genre.Name)
.Select(g => new CountOfVideos { Classification = g.Key, NumberOfMovies = g.Count() })
.ToList();
return View(movies);
}
视图:
@model IEnumerable<LinqTest.ViewModels.CountOfVideos>
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>Name</th>
<th>Count</th>
</tr>
</thead>
<tbody>
@foreach (var movie in Model)
{
<tr>
<td>@movie.Classification</td>
<td>@movie.NumberOfMovies</td>
</tr>
}
</tbody>
代码工作正常,但它没有显示其中没有视频的类型的名称。 View生成类似于:
动作23戏剧15但我想制作动作23戏剧15喜剧0恐怖0。
您应该从包含所需基础数据的集合开始。在这种情况下:类型。
就像是:
public ActionResult Movies() {
var genres = _context.Genres
.Select(g => new CountOfVideos {
Classification = g.Name, NumberOfMovies = g.Videos.Count()
})
.OrderBy(c => c.NumberOfMovies)
.ToList();
return View(genres);
}