C# 如何将 SQL 转换为 LINQ 查询

C# How to convert SQL into a LINQ query

我有一个 WinForms 应用程序通过 Entity Framework (EF 6) 连接到 Movies SQL 服务器数据库。

我有以下 SQL,我正在尝试将其转换为 LINQ 查询

SELECT 
    t.movieId,m.Title, t.number_of_files 
FROM 
    (SELECT mlf.movieId AS movieId, COUNT(*) AS number_of_files
     FROM MovieLinkFile mlf, "file" f
     WHERE f.path LIKE 'M:\%'
       AND f.id = mlf.fileId
     GROUP BY mlf.movieId
     HAVING COUNT(*) > 1) t
JOIN 
    Movie m ON t.movieId = m.Id
ORDER BY 
    m.title

这是我使用 LINQPad 对 LINQ 的尝试 http://www.linqpad.net/

from m in Movies
from mlf in Movielinkfiles
from f in Files
where m.Id == mlf.MovieId
      &&  mlf.FileId == Files.id
      && f.path.StartsWith ("M:\")
.GroupBy(x =>  x.movieId)
.where(c => c.count()  > 1)  // invalid expression
select m

连接到数据库的 C# 代码如下所示

private void LoadMovies()
{
    TitlesLV.Items.Clear();

    using (var context = new MoviesEntities())
    {
        // get a full list of all movies (will return everything from the database)
        var allMovies = context.movies.OrderBy(m => m.title).ToArray();

        foreach(var Movie in allMovies)
        {
            ListViewItem item = new ListViewItem();
            item.Text = Movie.title;
            item.Tag = Movie;

            TitlesLV.Items.Add(item);
        }
    }
}

数据库中有 3 个表:

如何在 C# 中编写 LINQ 语句?

要获取所有包含多个以“M:\”开头的文件的电影,请使用 CountPath.StartsWith 表达式,并检查 Count 的结果是否大于 1。

var filteredMovies = movies
    .Where(movie => movie.Files
        .Count(file => file.Path.StartsWith("M:\")) > 1
    )
    .OrderBy(movie => movie.Title);