Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/271.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 按嵌套表分组_C#_Linq_Entity Framework 4 - Fatal编程技术网

C# 按嵌套表分组

C# 按嵌套表分组,c#,linq,entity-framework-4,C#,Linq,Entity Framework 4,我有下列表格 [Order] [Product] ProductId [OrderDetails] OrderId ProductId Quantity 我必须使用Order对象获取一个列表,其中包含按销售额分组的产品总销售额 public class ProductSales { public decimal Total { get; set; } public Product Product { get; set; } } 给定订单对象列

我有下列表格

[Order]
[Product]
    ProductId
[OrderDetails]
    OrderId
    ProductId
    Quantity
我必须使用Order对象获取一个列表,其中包含按销售额分组的产品总销售额

public class ProductSales 
{
    public decimal Total { get; set; }
    public Product Product { get; set; }
}
给定订单对象列表,我应该如何选择其产品详细信息,然后按产品对销售进行分组

我当前的代码如下所示:

return Orders
       .Select(ordeDetail => new {
           Detail = ordeDetail.OrderDetails
                        .GroupBy(w => new {
                            Detail = w,
                             Product = w.Product})
        .Select (group => new ProductSales {
            Product = group.Key.Product, 
            Quantity = group.Sum(r => r.Quantity)
        })
        .ToList();

您可以按产品的ID或整行进行分组:

return Orders
   .Select(ordeDetail => new {
       Detail = ordeDetail.OrderDetails
                    .GroupBy(w=>w.Product)
                    .Select(w=>new ProductSales {
                       Product=w.Key,
                       Total=w.Sum(prod=>prod.Quantity) })
   })
   .ToList();

订单和产品是如何关联的?我猜每个订单都链接到一些OrderDetails行,每个订单都有自己的ProductId链接到Product,就像Blindy评论的那样,每个OrderDetails都有一个ProductId,更新的questionin}.GroupByd=>d.Detail.Product.ProductId Detail是一个EntityCollection,因此没有可用的产品实例在那里设置;我需要返回订购的产品和数量的列表,更新的问题也更新了我的-不知道为什么你一直坚持对产品本身以外的东西进行分组。GroupBy子句不是Select,它实际上是为了获得不同的数据存储桶而必须更改的内容。考虑到这一点,您可以按产品分组,然后选择产品,并使用Sum将产品的桶展平。可能缺少另一个选择?无法将类型“System.Collections.Generic.List”隐式转换为“System.Collections.Generic.ListI”我刚刚复制了您的初始化格式,显然您将其命名为Total,而不是Quantity。