Convert SQL into Linq query

安稳与你 提交于 2019-12-20 02:16:07

问题


I'm quite new at Linq queries, I just want to convert my DB query into Linq.

Here is my simple SQL query:

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

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

It is working fine , but how could it possible to write this query in Linq, I just can't convert the group by statement into Linq. It seems somewhat tricky to convert into Linq.

Can anyone help me with this?


回答1:


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



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


来源:https://stackoverflow.com/questions/16581089/convert-sql-into-linq-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!