c# - 使用 EF Core 将 SQL 转换为 Linq
问题描述
我正在使用 .NET Core 2.2、EF Core、C# 和 SQL Server 2017。我无法将需要的查询转换为 Linq。
这是我需要转换的查询:
SELECT TOP 5
p.Id,
p.Title,
AVG(q.RatingValue) AvgRating
FROM Movies AS p
INNER JOIN Ratings AS q ON p.Id = q.MovieId
GROUP BY p.Id, p.Title
ORDER BY AvgRating DESC, p.Title ASC
上一个查询的想法是根据 Avg 评分获得 Top 5 电影,首先按最高平均排序,如果平均排序相同,则按字母顺序排列。
到目前为止,这是我进行连接的查询,但仍然缺少:group by、average 和 ordering:
public class MovieRepository : IMovieRepository
{
private readonly MovieDbContext _moviesDbContext;
public MovieRepository(MovieDbContext moviesDbContext)
{
_moviesDbContext = moviesDbContext;
}
public IEnumerable<Movie> GetTopFive()
{
var result = _moviesDbContext.Movies.OrderByDescending(x => x.Id).Take(5).
Include(x => x.Ratings);
return result;
}
}
这些是实体:
public class Movie
{
public int Id { get; set; }
public string Title { get; set; }
public int YearOfRelease { get; set; }
public string Genre { get; set; }
public int RunningTime { get; set; }
public IList<Rating> Ratings { get; set; }
}
public class Rating
{
public int Id { get; set; }
public int MovieId { get; set; }
public int UserId { get; set; }
public decimal RatingValue { get; set; }
}
我也尝试使用 Linqer 工具将我的查询转换为 Linq,但它不起作用。
对于将查询转换为 LINQ 方法“GetTopFive”的任何帮助,我将不胜感激。
谢谢
解决方案
试试这个——
var data = _moviesDbContext.Movies.Include(x => x.Ratings)
.Select(x => new {
Id = x.Id,
Title = x.Title,
Average = (int?)x.Ratings.Average(y => y.RatingValue)
}).OrderByDescending(x => x.Average).ThenBy(x => x.Title).Take(5).ToList();
推荐阅读
- azure-devops - Azure DevOps 管道仅用于部署已更改的 arm 模板
- javascript - React 中的 Onclick 方法影响表格中的每个列表项,应该只影响被点击的那个
- memory-profiling - dotMemory - 快照中未列出的应用程序命名空间 - 仅是框架命名空间
- php - Wordpress:如何在页面上显示用户
- ios - 当 ObservedObject 在其他类中发生更改时如何在 ContentView 中运行方法 [Swift 5 iOS 13.4]
- swift - Curl 命令可在 CLI 上运行,但 Alamofire 无法进行身份验证
- c++ - 手动设置 cin.fail()
- php - PHP intl NumberFormatter::SPELLOUT 的源代码在哪里?
- sql - SQL 过滤掉具有多个列条目的行
- angular - 服务的依赖注入不起作用