具有多个SUM的ASP.NET核心实体框架SELECT

时间:2020-03-24 07:16:57

标签: asp.net-core asp.net-web-api

如何使用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 }
]

我被卡住了......

1 个答案:

答案 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();
}