使用 LINQ 获取销量较低的商品

我有 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; }

}

视图模型:


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);

}

使用此代码,我只能获得订单中销售量较低的产品。但我需要得到所有的产品,即使是那些从未售出的产品。


你能给我一些关于我该怎么做的建议吗?


尚方宝剑之说
浏览 155回答 1
1回答

慕桂英3389331

如果需要获取所有产品,则应查询产品表:public IActionResult LSProducts(){&nbsp; &nbsp;List<ProductSoldViewModel> model = new List<ProductSoldViewModel>();&nbsp; &nbsp;model = _context.Product&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .Include(a => a.OrderDetails)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .Select(o => new ProductSoldViewModel&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ProductCode = o.CodProduct,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ProductName = o.Nome,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Qty = o.OrderDetails.Sum(s => s.Qty)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.OrderBy(od => od.Qty)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.ToList();&nbsp; &nbsp;return View(model);}为了避免空异常,您可能需要将以下构造函数添加到您的模型中:public class Product{&nbsp; public Product()&nbsp; {&nbsp; &nbsp; &nbsp;OrderDetails = new HashSet<OrderDetail>();&nbsp; }&nbsp; (...)&nbsp; public ICollection<OrderDetail> OrderDetails { get; set; }}
打开App,查看更多内容
随时随地看视频慕课网APP