转换成SQL查询的Linq(Convert SQL into Linq query)

2019-09-03 14:16发布

我很新的LINQ查询,我只是想我的数据库查询转换为LINQ的。

这是我简单的SQL查询:

var query = "SELECT EnrollmentDate, COUNT(*) AS StudentCount "
          + "FROM Person "
          + "WHERE EnrollmentDate IS NOT NULL "
          + "GROUP BY EnrollmentDate";

var data = db.Database.SqlQuery<EnrollmentDateGroup>(query);

工作正常,但怎么可能有可能写在LINQ的这个查询 ,我只是不能转换为group by语句转换成Linq的。 这似乎有点棘手转换成Linq的。

谁能帮我这个?

Answer 1:

var result = db.Person
               .Where(r=> r.EnrollmentDate != null)
               .GroupBy(r=> r.EnrollmentDate)
               .Select( group=> new 
                              {
                                 EnrollmentDate = group.Key, 
                                 Count = group.Count()
                               });


Answer 2:

var query = from row in db.Person
            where row.EnrollmentDate != null
            group row by row.EnrollmentDate into grp
            select new {
                EnrollmentDate = grp.Key,
                Count = grp.Count()
            };


文章来源: Convert SQL into Linq query