0

I have 2 tables: OrderDetail and Product. I try to groupby IdProduct in OrderDetail table and retrieve ( Name in Product table, Quantity in OrderDetail). But I can't get the Name, only the key.

       public ActionResult GetData()
        {
            DbCon db = new DbCon();
            var query = db.OrderDetail.Include("Product")
                .GroupBy(p => p.Product_Id)
                .Select(g => new { name = g.Key ,count = g.Sum(w => w.Quanity) }).ToList();
            return Json(query, JsonRequestBehavior.AllowGet);
        }

//code highcharts

<script>
    $(document).ready(function () {
        $.getJSON("/Admin/Product/GetData", function (data) {
            var Names = []
            var Qts = []
            for (var i = 0; i < data.length; i++) {
                Names.push(data[i].name);
                Qts.push(data[i].count);
            }
            Highcharts.chart('container', {
                chart: {
                    type: 'line'
                },
                title: {
                    text: 'Thống kê các mặt hàng bán ra'
                },
                subtitle: {
                    text: ''
                },
                xAxis: {
                    categories: Names
                },
                yAxis: {
                    title: {
                        text: 'Số lượng bán ra'
                    }
                },
                plotOptions: {
                    line: {
                        dataLabels: {
                            enabled: true
                        },
                        enableMouseTracking: false
                    }
                },
                series: [{
                    name: 'Số lượng bán ra',
                    data: Qts
                }]
            });
        });
    });
</script>

Result: enter image description here

1 Answers1

0

To get the Product Name, you can apply GroupBy with Product_Id and ProductName as your Key.

The reason why GroupBy with Product_Id and ProductName but not ProductName as:

  1. Id is a unique identifier.
  2. Possible that Product Name will be duplicated in different products and leads to inaccurate calculation.

Next, retrieve the Product Name from Key.

var query = db.OrderDetail.Include("Product")
            .GroupBy(p => new { p.Product_Id, ProductName = p.Name })
            .Select(g => new { 
                name = g.Key.ProductName,
                count = g.Sum(w => w.Quanity) 
            }).ToList();
Yong Shun
  • 35,286
  • 4
  • 24
  • 46