gpt4 book ai didi

c# - 使用 EF Core 将 SQL 转换为 Linq

转载 作者:太空宇宙 更新时间:2023-11-03 22:37:26 25 4
gpt4 key购买 nike

我正在使用 .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 rating 获取 Top 5 电影,按最高平均分排序,如果平均分相同则按字母顺序排序。

到目前为止,这是我进行连接的查询,但仍然缺少:分组依据、平均值和排序:

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();

关于c# - 使用 EF Core 将 SQL 转换为 Linq,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54278900/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com