Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP NET CORE Entity Framework Select with GroupBy Id

I build a service to call query like this

select quotaId, sum(quota)
From leaveQuota
group by quotaId

I getting problem in sum and group. How to do it in Entity Framework i tried this

public async Task<List<LeaveTypeModel>> GetLeaveQuota(string employeeId)
{
  var leaveQuota = await DB.EmployeeLeaveQuota
    .Where(Q => Q.EmployeeId == employeeId && Q.ValidUntil >= DateTime.UtcNow)
    .Select(Q => new LeaveTypeModel
    {
        EmployeeLeaveQuotaTypeId = Q.EmployeeLeaveQuotaTypeId,
        QuotaDays = Q.QuotaDays
    })
    .ToListAsync();

    return leaveQuota;
  }

my model

public class LeaveTypeModel
{
    public int EmployeeLeaveQuotaTypeId { set; get; }
    public int QuotaDays { set; get; }
}

if i use .GroupBy i cant return it as my model and i have no idea to sum my quotadays column

i know it is a basic query, but i'm not familiar yet with entity framework and asp.net core to return its data

like image 344
hphp Avatar asked Mar 06 '23 22:03

hphp


1 Answers

var leaveQuota = await DB.EmployeeLeaveQuota
    .Where(Q => Q.EmployeeId == employeeId && Q.ValidUntil >= DateTime.UtcNow)
    .GroupBy(x => x.EmployeeLeaveQuotaTypeId).Select(x => 
    new LeaveTypeModel
    {
        EmployeeLeaveQuotaTypeId = x.Key,
        QuotaDays = x.Sum(y => y.QuotaDays)
    }).ToListAsync();
like image 65
Slava Utesinov Avatar answered Mar 19 '23 03:03

Slava Utesinov