Good day!

I have a client in C # and SQLServer 2012. I use EF6 to connect.

I write something like this:

using (PCMSContext context = new PCMSContext()) { Dictionary<Guid, pidPV> pPVs = context.pidPV.GroupBy(e => e.idPID).Select(g => g.OrderByDescending(f => f.date).FirstOrDefault()).ToDictionary(e => e.idPID); } 

I care about the minimum load on the network and the client, respectively, I have a question of the following plan:

Up to what point is this LINQ query translated to SQL database query?

It is important that the operation g => g.OrderByDescending(f => f.date).FirstOrDefault() performed on the database side, since pidPV just a huge number of pidPV rows in the table and I don’t need to load them all onto the client and do the sorting and fetching of the first element locally on the client.

I know that ToDictionary() in any case executed on the client side, because this extension method works with a collection that implements IEnumerable.

Is g => g.OrderByDescending(f => f.date).FirstOrDefault() on the SQLServer side in this case?

  • In a nutshell: IEnumerable is client-side, IQueryable is server-side. Read well let's say: metanit.com/sharp/entityframework/1.4.php - AK
  • 3
    Yes, everything before ToDictionary executed on the server. Before executing the query, you can hang a logger on the Log property and see which sql is generated. The easiest: context.Database.Log += Console.WriteLine; - Alexander Petrov
  • As far as I know the execution of the First method happens on the client side. - Bald
  • one
    @Bald, you're wrong, or not completely right :-) First is Top (1) - Grundy
  • 2
    In both cases in sql will be TOP (1) . And already on the client, if NULL came from the database, in the case of First exception will be thrown, and in the case of FirstOrDefault will be null . - Alexander Petrov

0