我有下表:
罐 Id:int HospitalId :(外键)int operDt:DateTime
我需要计算按hospitalId分组的罐行总数
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();
};
}
控制器:
[HttpGet("bydate")]
public IActionResult GetCanMin(DateTime startdt, DateTime endd)
{
var res = this._unitOfWork.Cans.GetCansMin(startdt, endd);
return Ok(res);
}
用邮递员传递请求时:
http://localhost:56964/api/cansdatas/bydate?startdt=2016-01-01&enddt=2016-12-31
而不是接收结果数组我得到一个空对象.... 你能帮忙吗?
答案 0 :(得分:1)
由于您调用的方法是异步的,因此您需要等待返回的任务。
[HttpGet("bydate")]
public async Task<IActionResult> GetCanMin(DateTime startdt, DateTime endd)
{
var res = await this._unitOfWork.Cans.GetCansMin(startdt, endd);
return Ok(res);
}
答案 1 :(得分:0)
创建了一个视图模型
public class CancelledCan
{
public int HospitalId { get; set; }
public int NumberofCancelled { get; set; }
}
将存储库更改为
public async Task<List<CancelledCan>> GetCansMin(DateTime startdt, DateTime enddt)
{
using (appContext)
{
return await appContext.Cans.Where(c => c.OperDt > startdt && c.OperDt < enddt).GroupBy(c => c.HospitalId).OrderBy(c=>c.Count())
.Select(g => new CancelledCan
{
HospitalId = g.Key,
NumberofCancelled = g.Count()
}).ToListAsync();
};
}