首页 > 解决方案 > 使用 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”的任何帮助,我将不胜感激。

谢谢

标签: c#entity-frameworklinq-to-sql.net-corerepository-pattern

解决方案


试试这个——

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

推荐阅读