Home > Enterprise >  Converting SQL query into Linq which used complex sum with group by
Converting SQL query into Linq which used complex sum with group by

Time:12-01

Here is my Service table's columns:

id
serverPlace
count

Here is a SQL query which I need to convert it into Linq:

 SELECT Service.id,
    Service.serverPlace,
    sum(Service.count * 12   MONTH(getdate())) AS sum
   FROM Service
  GROUP BY Service.id, Service.serverPlace;

I do not know how to convert and implement sum section with Linq.

CodePudding user response:

It should look like this :

var month = DateTime.Now.Month;
var result = await dbContext.Services.GroupBy(r=> new { r.Id, r.ServerPlace })
            .Select(r=> new {
             r.Key.Id,
             r.Key.ServerPlace,
             Sum = r.Sum(q=> q.Count*12   month)
            }).ToArrayAsync();
  • Related