【问题标题】:Lookup / Join with LINQ-to-Entities in C#在 C# 中使用 LINQ-to-Entities 查找/加入
【发布时间】:2011-05-25 19:38:04
【问题描述】:

我有一个包含两个表的数据库:订单和产品。该数据库通过实体数据模型和 LINQ-to-Entities 公开。

我有一个产品 ID,我想获取所有引用该产品的 Order 对象。我想学习如何使用 LINQ 做到这一点。我知道我可以查询产品

int productID = GetProductID();
using (DatabaseContext database = new DatabaseContext())
{
  var products = from product in database.Products
               where product.ProductID = productID
               select product;

}

我知道这个 LINQ 查询可以让我获得具有特定产品 ID 的所有产品。但是,我想要 Order 对象。我试图弄清楚做一个 Join 并获得 Order 对象。我不关心产品,因为我有产品 ID。有没有办法做到这一点?

谢谢!

【问题讨论】:

  • Orders 表没有直接被数据上下文暴露?
  • 产品和订单之间是多对多的关系吗?
  • 你应该有 Order.ProductID。
  • 订单和产品有哪些相关属性?

标签: c# linq-to-entities


【解决方案1】:
 var orders = from product in database.Products
            join order in database.Orders on product.Key equals order.KeyField 
           where product.ProductID == productID
           select order;

【讨论】:

  • 请注意,如果一个订单多次包含相同的产品,则可能会多次给出相同的订单。这可能不是问题,但值得了解。
【解决方案2】:

通常Order 与产品有关系,允许您写:

var orders = from order in database.Orders
             where order.Products.Any(p => p.ProductID == productID)
             select order;

【讨论】:

    【解决方案3】:

    通常,这将是这样完成的:

    为了简单起见:[TABLE] <key/relation>

    [Products]-<productId>-[OrderedProducts]-<orderId>-[Orders]
    
    var result = 
    from op in OrderedProducts
    join o in Orders on op.OrderId equals o.Id
    join p in Products on op.ProductId equals p.Id
    select p
    

    【讨论】:

      【解决方案4】:

      类似的东西(取决于您拥有的属性):

      context.Orders.Where(order => order.ProductId == myProduct.Id);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多