如何使用ASP.NET Core API将多个SUM作为JSON字符串返回?
型号:
public class PriceSum
{
public int sum1 {get;set;}
public int sum2 {get;set;}
public int sum3 {get;set;}
}
常规T-SQL:
SELECT
SUM(field1) AS sum1,
SUM(field2) AS sum2,
SUM(field3) AS sum3
FROM
Prices
WHERE
ProdId = Id
API控制器:
[HttpGet("pricesums/{id}")]
public IEnumerable<PriceSum> GetSums(int id)
{
return _context.DbPriceSums
.Where(p => p.Id == id)
.Sum(p => p.field1).ToList();
}
我的退货应该是这样
[
{ "sum1":1000, "sum2":2000, "sum3":3000 }
]
我被卡住了......
答案 0 :(得分:0)
您可以这样做:
[HttpGet("pricesums/{id}")]
public IEnumerable<PriceSum> GetSums(int id)
{
return _context.DbPriceSums
.Where(p => p.Id == id)
.Select(x => new PriceSum {
sum1 = x.field1.Sum() ,
sum2 = x.field2.Sum() ,
sum3 = x.field3.Sum()
}).ToList();
}