Search code examples
asp.netasp.net-mvcentity-frameworklambdalinq-to-entities

How to convert sql limit query to linq lambda?


Here's an example that I want to convert to lambda query:

SELECT TOP(5) Pbschedules.s_id, Pbschedules.date, Pbworth2.worth, Pbschedules.pb_id 
FROM Pbschedules INNER JOIN Pbworth2 ON Pbschedules.pb_id = Pbworth2.pb_id
ORDER BY s_id desc

Solution

  • var query = database.Pbschedules// your starting point - table in the "from" statement
      .Join(database.Pbworth2, // the source table of the inner join
      pbs=> pbs.pb_id,        // Select the primary key (the first part of the "on" clause in an sql "join" statement)
      worth=> worth.pb_id,   // Select the foreign key (the second part of the "on" clause)
      (pbs, worth) => new { PbsID = pbs.s_id, Worth = worth.worth /*other columns*/ }) // selection
      .OrderByDescending(x => x.s_id)      
      .Take(5);