Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does LINQ load every object in a request?

Tags:

c#

linq

Let me explain my self.

With the help of LINQ i'm requesting an object to my database such :

int idGetClient=1;
Client clientToUpdate = context.Client.FirstOrDefault(p=>p.idClient == idGetClient);

in my Model, a client is related to another object called Site. So i can easily get my Site object from my SQL database just by calling :

Site siteToUpdate = clientToUpdate.Site;

So i wonder what's happening here, did LINQ ALREADY loaded up the result in my first request OR is he requesting again taking up my client information and looking up in my database ?

The second one looks the most logic to me but i want to make sure, since if what happen if the first case, it's going to cause some performance issues.

like image 256
Fortune Avatar asked Mar 08 '26 15:03

Fortune


2 Answers

If nothing else is specified, your property Site will be lazy loaded, so just at the moment you try to access to the property, Entity will query the database server.

If a second access to the database server will cause performance issue, you can prevent that with:

  int idGetClient=1;
  Client clientToUpdate = context.Client
                                 .Include("Site")
                                 .FirstOrDefault(p=>p.idClient == idGetClient);

And you can add as many Include as you want, and you can even load properties of properties :

  int idGetClient=1;
  Client clientToUpdate = context.Client
                                 .Include("Site")
                                 .Include("Site.SubProperty")
                                 .FirstOrDefault(p=>p.idClient == idGetClient);

The Include will force the eager loading of the specified properties.

More info here : https://msdn.microsoft.com/en-us/data/jj574232.aspx

like image 91
Fumidu Avatar answered Mar 10 '26 16:03

Fumidu


Presuming you are using entity framework, you can hook into the sql statements yourself and see what's going on when you access your object - e.g.

 context.Database.Log = Console.Write; 

It's also possible to ensure the relation is loaded by using include:

context.Client.Include("Site").FirstOrDefault(p=>p.idClient == idGetClient);
like image 31
NDJ Avatar answered Mar 10 '26 16:03

NDJ