views:

463

answers:

1

How to translate the following query to Linq?

  SELECT DISTINCT TOP 10 A.*,A.X+A.Y AS SUMXY
  FROM TABLE_A AS A INNER JOIN TABLE_B AS B ON A.ID = B.AID
  ORDER BY SUMXY

I don't want to split in two queries.

+5  A: 

Using extension methods and assuming you have a foreign key relationship between Table_A and Table_B so that there is an EntitySet named TableBs on the TableAs table (this would be easier using real table names... sigh).

var query = db.TableAs.Where( a => a.TableBs.Count() > 0 )
                      .Select( a => new { A = a, SumXY = a.X + a.Y } )
                      .OrderBy( a => a.SumXY )
                      .Take( 10 );

This will give you back a collection of anonymous-typed objects having an TableA object named A and a SumXY (an int, presumably). Alternatively, you could create a real class that holds A's data plus the sum and select objects of this type.

tvanfosson