ServicesResourcesConferencesOur TeamWeblogsAboutContact
   

Subscriptions

Post Categories

News

My new books

My Blogroll

INETA UG Leaders

Affiliations

News

Archives

Christian Nagel's OneNotes

.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

posted on Monday, February 18, 2008 11:58 PM

# LINQ and Lambdas and Sprocs....Oh My! @ Friday, February 22, 2008 8:28 AM

There's a lot of great stuff in .NET 3.5 and several different ways to work with LINQ technologies such
Dan Wahlin's WebLog


Powered by Community Server, by Telligent Systems