【问题标题】:LINQ Unable to get distinct value from many to many Entity FrameworkLINQ 无法从多对多实体框架中获得不同的价值
【发布时间】:2017-01-03 08:10:13
【问题描述】:

我正在使用 linq 查询多对多关系

我有那些表/实体:

每个订单都有多个产品,我想获得不同的产品订单。

这是我的查询:

var query = (from order in db.Order
             join orderproduct in db.OrderProduct
                         on order.orderId equals orderproduct.OrderId
             join product in db.Product
                         on orderproduct.ProductId equals product.productId
             select new 
                    { order.orderId, 
                      order.name,
                      product.productId, 
                      product.productName, 
                      product.price 
                    }).Distinct().ToList();

这是结果:

我只想获得包含 2 个产品的名称“Jane”。结果显示2条同名“Jane”的记录。

如何获得一个记录名称“jane”和2个产品?

感谢您的帮助。

【问题讨论】:

  • 为了获得带有 2 个产品的“Jane”,您必须使用 group by
  • 您必须按我会说的 orderId 或名称对数据进行分组。

标签: c# linq


【解决方案1】:

使用以下内容:

var query = (from order in db.Order
                         join orderproduct in db.OrderProduct
                         on order.orderId equals orderproduct.OrderId
                         join product in db.Product
                         on orderproduct.ProductId equals product.productId
                         select new {order.orderId,order.name,product.productId,product.productName,product.price}).GroupBy(order=>order.orderId).ToList();

【讨论】:

  • @timothy 他的回答是正确的。一定要复制他所有的代码。
【解决方案2】:

如果您想返回包含客户姓名及其订购产品的结构,我建议您按 order.orderName(而不是 order.orderId)对产品进行分组并将结果加载到字典中:

var query = from order in db.Order
            join orderproduct in db.OrderProduct on order.orderId equals orderproduct.OrderId
            join product in db.Product on orderproduct.ProductId equals product.productId
            group product by order.orderName into orderGroup
            select orderGroup;

var orderedProductsByName = query.ToDictionary(name => name.Key, products => products.ToList());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-10
    • 1970-01-01
    • 2015-09-05
    • 1970-01-01
    • 2016-12-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多