Export (0) Print
Expand All

How to: Handle Composite Keys in Queries (LINQ to SQL)

Some operators can take only one argument. If your argument must include more than one column from the database, you must create an anonymous type to represent the combination.

The following example shows a query that invokes the GroupBy operator, which can take only one key argument.

        var query =
from cust in db.Customers
group cust.ContactName by new { City = cust.City, Region = cust.Region };

        foreach (var grp in query)
        {
            Console.WriteLine("\nLocation Key: {0}", grp.Key);
            foreach (var listing in grp)
            {
                Console.WriteLine("\t{0}", listing);
            }
        }

The same situation pertains to joins, as in the following example:

        var query =
from ord in db.Orders
from prod in db.Products
join det in db.OrderDetails
    on new { ord.OrderID, prod.ProductID } equals new { det.OrderID, det.ProductID }
    into details
from det in details
select new { ord.OrderID, prod.ProductID, det.UnitPrice };

Community Additions

ADD
Show:
© 2014 Microsoft