Linq to Entities Group By 那里有一些没有元素的组
Linq to Entities Group By where there are some groups with no elements
型号类:
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; }
}
例如类型名称是:动作、戏剧、喜剧和恐怖。
没有喜剧和恐怖类型的视频。
查看模型Class:
public class CountOfVideos
{
public string Classification { get; set; }
public int NumberOfMovies { get; set; }
}
控制器Class:
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>
代码工作正常,但它不显示其中没有视频的流派名称。
视图生成如下内容:
行动23
戏剧15
但我想生成 Action 23 Drama 15 Comedy 0 Horror 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);
}
型号类:
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; }
}
例如类型名称是:动作、戏剧、喜剧和恐怖。 没有喜剧和恐怖类型的视频。
查看模型Class:
public class CountOfVideos
{
public string Classification { get; set; }
public int NumberOfMovies { get; set; }
}
控制器Class:
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>
代码工作正常,但它不显示其中没有视频的流派名称。 视图生成如下内容:
行动23 戏剧15 但我想生成 Action 23 Drama 15 Comedy 0 Horror 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);
}