Lookup / Join with LINQ-to-Entities in C#
I have a database that has two tables: Order and Product. This database is exposed via an Entity Data Model and LINQ-to-Entities.
I have a product ID and I want to get all of the Order objects that reference the Product. I would like to learn how to do this with LINQ. I know I can query the products
int productID = GetProductID();
using (DatabaseContext database = new DatabaseContext())
{
var products = from product in database.Products
where product.ProductID = productID
select product;
}
I know this LINQ query get me all of the products with a specific product ID. However, I want the Order objects. I was trying to figure out to do a Join and get the just the Order object开发者_如何学Cs. I do not care about the products as I have the product id. Is there a way to do this?
Thank you!
var orders = from product in database.Products
join order in database.Orders on product.Key equals order.KeyField
where product.ProductID == productID
select order;
Normally an Order
would have a relationship to the products, allowing you to write:
var orders = from order in database.Orders
where order.Products.Any(p => p.ProductID == productID)
select order;
Typically, this would be done like this :
For the sake of simplicity : [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
Something like (depending on properties you have):
context.Orders.Where(order => order.ProductId == myProduct.Id);
精彩评论