我是Linq查询的新手,我只是想将我的DB查询转换为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似乎有点棘手。
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()
};
var result = db.Person
.Where(r=> r.EnrollmentDate != null)
.GroupBy(r=> r.EnrollmentDate)
.Select( group=> new
{
EnrollmentDate = group.Key,
Count = group.Count()
});