Home > Mobile >  IQueryable: Select new triggers eager loading?
IQueryable: Select new triggers eager loading?

Time:10-14

I'm trying to understand how linq queries are executed.

As I know IQueryable queries are evaluated on server side together with filters and select and are executed only when ToList() or First() method is called.

However I'm having troubles understanding how the following query is evaluated. Is the "select new" evaluated on client side or on server side?

Is the Select(x=> new Note) triggers eager loading ?

IQueryable<Note> query = db.Notes
                           .Where(x => Id == someId)
                           .Select(c => new Note 
                                            {
                                                Title = x.Title
                                                Id = x.NoteId,
                                            });

CodePudding user response:

In your case Select new is a instruction how to map DbDataReader fields to Note object. Member access parts like x.Title is translated to reader instruction like dbReader.GetString(0).

Internally LINQ Translator generates SQL for retrieving data

SELECT 
    x.Title,
    x.NoteId
FROM Notes x
WHERE x.Id = @someId

And generates LambdaExpression (schematically)

(DbDataReader dr) => new Note
{
    Title = dr.GetString(0),
    Id = dr.GetInt32(1)
}

Then this LambdaExpression is compiled and cached. When LINQ Provider executes query via ToList(), ToArray(), etc, generated SQL is sent to the Database and starts process of enumerating DataReader. For each DataReader record applied above compiled lambda. It makes from IQueryable<Note> (server side) IEnumerable<Note> (client side).

This VERY simple explanation what is done under hood.

  • Related