Lazy Loading Related Properties

Lot of times in our application we do not perform eager loading on related entities because we don’t need to display them on the UI unless some action occurs. So we fetch those entities lazily only when we need them. However have you ever felt the need to lazily fetch several related entities? Suppose we have a model consisting officers who gave tickets to Drivers as shown below.

image

 

Let’s say on the user interface we are displaying Officer information and based on some action on the user interface, we want to display the Tickets the officer gave along with the driver information. Now we could lazily fetch the tickets and the driver for each ticket separately but this would be numerous database calls. To solve such a problem, we could use CreateSourceQuery method available on Collection navigation property. Code below shows an example.

 

image

In the above code, we use CreateSourceQuery method to grab the query that EF uses to fetch the tickets collection. We then modify the query with an Include operator to also fetch the Drive for each ticket as well. Notice that we have explicitly turned off LazyLoading on the above code because when you use CreateSourceQuery  on a collection property(works fine on entity reference), you are telling EF that I am taking responsibility of loading the collection. Hence it cannot guarantee that entire Tickets collection was fetched or not.  Therefore if you have lazy loading turned on and you access the tickets property, there will be a database call being made because officer.Tickets.IsLoaded would be false.

The above code seems really nice but only works with default code generator because all collection navigation properties return EntityCollection which exposes the CreateSourceQuery method. What happens if you are using poco. Well for that you have to wait for my next blog post!

No Comments