|
|
|
|
.NET Training, Consulting, Coaching & Development
LINQ with joins
|
Dan Wahlin posts about LINQ and Lambdas and Sprocs... Oh My!
With his post he defines a complex LINQ query to join several tables from the Northwind database:
public IEnumerable
GetOrderDetails(int orderID)
{
NorthwindDataContext db = this.DataContext;
IEnumerable orderDetails =
from o in db.Orders
where o.OrderID == orderID
join s in db.Shippers on o.ShipVia equals s.ShipperID
join od in db.OrderDetails on o.OrderID equals od.OrderID
join p in db.Products on od.ProductID equals p.ProductID
join supplier in db.Suppliers on p.SupplierID equals supplier.SupplierID
let total = od.Quantity * od.UnitPrice
select new OrderDescription
{
Product = p.ProductName,
Quantity = od.Quantity,
ShipperName = s.CompanyName,
Total = total,
UnitPrice = od.UnitPrice,
SupplierName = supplier.CompanyName
};
return orderDetails;
}
Instead of using joins with the LINQ query expression it is also possible to use compound from and access shipper and supplier (with a * to 1 relation) directly:
public IEnumerable
GetOrderDetails(int orderID)
{
NorthwindDataContext db = this.DataContext;
IEnumerable orderDetails =
from o in db.Orders
where o.OrderID == orderID
from od in o.OrderDetails
let total = od.Quantity * od.UnitPrice
select new OrderDescription
{
Product = od.Product.ProductName,
Quantity = od.Quantity,
ShipperName = o.Shipper.CompanyName,
Total = total,
UnitPrice = od.UnitPrice,
SupplierName = od.Product.Supplier.CompanyName
};
return orderDetails;
}
I think the LINQ query with compound from is the simpler one.
Christian
|
© 2002 - 2006 by thinktecture, Ingo Rammer and Christian Weyer. All rights reserved.

|
|