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.

Dim query = _
From cust In db.Customers _
Group cust.ContactName By Key = New With {cust.City, cust.Region} _
Into Group

For Each grp In query
    Console.WriteLine("Location Key: {0}", grp.Key)
    For Each listing In grp.Group
        Console.WriteLine(vbTab & "0}", listing)
    Next 
Next

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

Dim query = From ord In db.Orders, prod In db.Products _
    Join det In db.OrderDetails _
    On New With {ord.OrderID, prod.ProductID} Equals _
    New With {det.OrderID, det.ProductID} _
    Select ord.OrderID, prod.ProductID, det.UnitPrice

Community Additions

ADD
Show:
© 2015 Microsoft