Click here to Skip to main content
15,888,124 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have the following table:

<pre lang="c++">Cans
 
Id: int 
HospitalId: (Foreign Key) int 
operDt: DateTime


I need to calculate the total number of cans rows grouped by hospitalId

to get a similar result without Id

screenshot[^]

What I have tried:

The repository :

C++
public Task GetCansMin(DateTime startdt, DateTime enddt)
            {
                using (appContext)
                {
                    return appContext.Cans.Where(c => c.OperDt > startdt && c.OperDt < enddt).GroupBy(c => c.HospitalId)
                          .Select(g => new
                          {
                              NumberofCancelled = g.Count() 
                          }).ToArrayAsync();
                         
                };
            }


The controller:



C++
[HttpGet("bydate")]
            public IActionResult GetCanMin(DateTime startdt, DateTime endd)
            {
                var res = this._unitOfWork.Cans.GetCansMin(startdt, endd);
                return Ok(res);
            }


When passing the request with postman:

C#
http://localhost:56964/api/cansdatas/bydate?startdt=2016-01-01&enddt=2016-12-31


instead of receiving an array of results I get an empty object....
Could you help?
Posted
Updated 6-Nov-17 7:06am
v3

1 solution

You're returning a Task, rather than the results of that Task.

You're also disposing of the DbContext before the Task has completed.

(There's also a missing "t" in the action parameter name, but I'm not sure whether that's just a typo in your question.)

Try something like this:
C#
public async Task<object> GetCansMin(DateTime startdt, DateTime enddt)
{
    using (appContext)
    {
        return await appContext.Cans
            .Where(c => c.OperDt > startdt && c.OperDt < enddt)
            .GroupBy(c => c.HospitalId)
            .Select(g => new
            {
                NumberofCancelled = g.Count() 
            })
            .ToArrayAsync();
                         
    }
}

[HttpGet("bydate")]
public async Task<IActionResult> GetCanMin(DateTime startdt, DateTime enddt)
{
    var res = await this._unitOfWork.Cans.GetCansMin(startdt, enddt);
    return Ok(res);
}

NB: Since you're storing the DbContext in a field, I'd be inclined to remove the using (appContext) blocks from your methods, and have your unit-of-work class implement IDisposable instead. You can then register that class to be disposed after each request:
Four ways to dispose IDisposables in ASP.NET Core[^]
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900