使用LINQ获得减价商品

时间:2018-07-26 10:09:11

标签: c# asp.net-mvc linq asp.net-core

我有2个对象(订单和产品)和第三个对象(OrderDetail),将用作“产品”和“订单”之间的“导航”。

我正在尝试构建一个视图,以显示销售较少的产品。为此,我要“查询”对象OrderDetail并将结果保存在视图模型中,以供以后在视图中使用。

型号:

public class Product
{
  public int ProductID { get; set; }
  public string CodProduct { get; set; }
  public string Nome { get; set; }
  (...)
  public ICollection<OrderDetail> OrderDetails { get; set; }
}

public class Order
{
  public int OrderID { get; set; }
  (...)
  [BindNever]
  public ICollection<OrderDetail> OrderDetails { get; set; }
}

public class OrderDetail
{
  public int OrderDetailId { get; set; }
  public int OrderId { get; set; }
  public int ProductID { get; set; }
  public int Quantity { get; set; }
  public decimal UnitPrice { get; set; }
  public virtual Product Product { get; set; }
  public virtual Order Order { get; set; }
}

ViewModel:

public class ProductSoldViewModel
{
    //Data from the Product
    public string ProductCode { get; set; }
    public string ProductName { get; set; }
    //Data from the OrderDetail
    public int Qty { get; set; }
}


控制器:

public IActionResult LSProducts()
{
   List<ProductSoldViewModel> model = new List<ProductSoldViewModel>();

   model = _context.OrderDetail
            .GroupBy(od => od.ProductID)
            .Select(o => new ProductSoldViewModel
            {
                ProductCode = o.Select(s => s.Product.CodProduct).FirstOrDefault(),
                ProductName = o.Select(s => s.Product.Nome).FirstOrDefault(),
                Qty = o.Sum(s => s.Quantity)
            })
         .OrderBy(od => od.Qty)
         .ToList();

   return View(model);
}

使用此代码,我只能得到订单中存在的未售出产品。但是我需要获得所有产品,甚至包括从未售出的产品。

您能给我一些建议吗?

1 个答案:

答案 0 :(得分:2)

如果需要获取所有产品,应查询产品表:

public IActionResult LSProducts()
{
   List<ProductSoldViewModel> model = new List<ProductSoldViewModel>();

   model = _context.Product
            .Include(a => a.OrderDetails)
            .Select(o => new ProductSoldViewModel
            {
                ProductCode = o.CodProduct,
                ProductName = o.Nome,
                Qty = o.OrderDetails.Sum(s => s.Qty)
            })
         .OrderBy(od => od.Qty)
         .ToList();

   return View(model);
}

为避免出现空异常,您可能需要向模型中添加以下构造函数:

public class Product
{
  public Product()
  {
     OrderDetails = new HashSet<OrderDetail>();
  }

  (...)

  public ICollection<OrderDetail> OrderDetails { get; set; }
}