如何在web api中获取子表的总和?

时间:2014-11-25 18:26:38

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

这是我的订单型号:

    public class Order
{
    [Key]
    public int OrderID { get; set; }
    [Column(TypeName = "Date")]
    public DateTime? OrderDate { get; set; }
    public string OrderStatus { get; set; }
    public string CreatedBy { get; set; }
    public DateTime? CreatedDate { get; set; }
    public DateTime? ModifiedDate { get; set; }
    public int? Active { get; set; }
    public int? CreditorID { get; set; }
    public virtual Creditor Creditor { get; set; }
    public virtual ICollection<OrderItem> OrderItems { get; set; }
}

这是我的OrderItem模型:

    public class OrderItem
{
    [Key]
    public int OrderItemID { get; set; }
    public string ItemDescription { get; set; }
    public int ItemQty { get; set; }
    public decimal ItemUnitPrice { get; set; }
    public int ItemTaxGroup { get; set; }
    public decimal ItemTotalTax { get; set; }
    public decimal ItemTotalPrice { get; set; }
    public int OrderID { get; set; }
    public virtual Order Order { get; set; }
}

这是我当前的控制器查询:

return db.Orders.Where(order => order.Active == 1);

返回以下json:

{"OrderID":3,"OrderDate":"2014-11-26T00:00:00","OrderStatus":"Draft"},
{"OrderID":4,"OrderDate":"2014-11-26T00:00:00","OrderStatus":"Draft"},
{"OrderID":5,"OrderDate":"2014-11-26T00:00:00","OrderStatus":"Draft"}

使用SQL这是我需要它返回的(相关OrderItems的总和):

SELECT PT.*, (SELECT SUM([ItemTotalPrice]) FROM [OrderItems] AS CT WHERE CT.OrderID = PT.OrderID) AS OrderTotal
FROM [Orders] AS PT
WHERE PT.Active = 1

这就是我需要它在json中返回的内容:

{"OrderID":3,"OrderDate":"2014-11-26T00:00:00","OrderStatus":"Draft","OrderTotal":189.95},
{"OrderID":4,"OrderDate":"2014-11-26T00:00:00","OrderStatus":"Draft","OrderTotal":88.0},
{"OrderID":5,"OrderDate":"2014-11-26T00:00:00","OrderStatus":"Draft","OrderTotal":0.0}

1 个答案:

答案 0 :(得分:0)

您需要为商品选择一个新商品,我不确定您的设置是什么,但您可能需要创建一个新的模型/视图模型来保存您的数据。这样的事情

public class OrderViewModel {
    public int OrderId {get; set;}
    public DateTime OrderDate {get; set;}
    public string OrderStatus {get; set;}
    public decimal OrderTotal {get; set;}
}

然后你的选择会沿着这些线看,

var orders = (from o in Orders
                where o.Active == 1
                select new OrderViewModel   
                            { OrderId = o.OrderId,
                              OrderDate = o.OrderDate,
                              OrderStatus = o.OrderStatus,
                              OrderTotal = o.OrderItems.Sum(oi => oi.ItemTotalPrice)
                            });