将SQL转换为Linq查询

时间:2013-05-16 07:09:32

标签: c# linq sql-to-linq-conversion

我对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似乎有些棘手。

任何人都可以帮我吗?

2 个答案:

答案 0 :(得分:15)

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

答案 1 :(得分:10)

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