Understanding Lazy Loading , Eager Loading and Explicit Loading with Entity Framework Implementation

In this article we are going to understand and differentiate between Lazy Loading, Eager Loading and Explicit Loading, first of all let’s define what are those.

Lazy Loading :

Lazy loading is a design pattern commonly used in computer programming to defer initialization of an object until the point at which it is needed. It can contribute to efficiency in the program’s operation if properly and appropriately used. In other words when objects are returned by a query, related objects are not loaded at the same time. Instead they are loaded automatically when the navigation property is accessed.

Eager Loading :

Eager loading is the opposite of Lazy loading which is : The process of loading a specific set of related objects along with the objects that were explicitly requested in the query.

Explicit Loading :

Explicit loading is defined as : when objects are returned by a query, related objects are not loaded at the same time. By default, they are not loaded until explicitly requested using the Load method on a navigation property.

Let’s try those three ways practically.

First create a project and use preferred tool to generate your DbContext , in my example I will use Northwind as a database , ADO.NET Entity Data Model and for class generator EF 4.x  DbContext Class Generator.

Add a MVC3 website project to your solution and start typing on HomeController the Index method :

start your SqlProfiler and notice in this case we have 4 queries which means calling the database 4 times , one for the categories and three times for the products associated to the categories

First query

[c].[CategoryID] AS [CategoryID],
[c].[CategoryName] AS [CategoryName],
[c].[Description] AS [Description],
[c].[Picture] AS [Picture]
FROM [dbo].[Categories] AS [c]

Second query

exec sp_executesql N’SELECT
[Extent1].[ProductID] AS [ProductID],
[Extent1].[ProductName] AS [ProductName],
[Extent1].[SupplierID] AS [SupplierID],
[Extent1].[CategoryID] AS [CategoryID],
[Extent1].[QuantityPerUnit] AS [QuantityPerUnit],
[Extent1].[UnitPrice] AS [UnitPrice],
[Extent1].[UnitsInStock] AS [UnitsInStock],
[Extent1].[UnitsOnOrder] AS [UnitsOnOrder],
[Extent1].[ReorderLevel] AS [ReorderLevel],
[Extent1].[Discontinued] AS [Discontinued]
FROM [dbo].[Products] AS [Extent1]
WHERE [Extent1].[CategoryID] = @EntityKeyValue1′,N’@EntityKeyValue1 int’,@EntityKeyValue1=1

Third query

exec sp_executesql N’SELECT
[Extent1].[ProductID] AS [ProductID],
[Extent1].[ProductName] AS [ProductName],
[Extent1].[SupplierID] AS [SupplierID],
[Extent1].[CategoryID] AS [CategoryID],
[Extent1].[QuantityPerUnit] AS [QuantityPerUnit],
[Extent1].[UnitPrice] AS [UnitPrice],
[Extent1].[UnitsInStock] AS [UnitsInStock],
[Extent1].[UnitsOnOrder] AS [UnitsOnOrder],
[Extent1].[ReorderLevel] AS [ReorderLevel],
[Extent1].[Discontinued] AS [Discontinued]
FROM [dbo].[Products] AS [Extent1]
WHERE [Extent1].[CategoryID] = @EntityKeyValue1′,N’@EntityKeyValue1 int’,@EntityKeyValue1=2

Fourth query

exec sp_executesql N’SELECT
[Extent1].[ProductID] AS [ProductID],
[Extent1].[ProductName] AS [ProductName],
[Extent1].[SupplierID] AS [SupplierID],
[Extent1].[CategoryID] AS [CategoryID],
[Extent1].[QuantityPerUnit] AS [QuantityPerUnit],
[Extent1].[UnitPrice] AS [UnitPrice],
[Extent1].[UnitsInStock] AS [UnitsInStock],
[Extent1].[UnitsOnOrder] AS [UnitsOnOrder],
[Extent1].[ReorderLevel] AS [ReorderLevel],
[Extent1].[Discontinued] AS [Discontinued]
FROM [dbo].[Products] AS [Extent1]
WHERE [Extent1].[CategoryID] = @EntityKeyValue1′,N’@EntityKeyValue1 int’,@EntityKeyValue1=3

So in Lazy Loading pattern the Object comes with its associated/related Objects.

Now let’s turn off Lazy Loading and try Eager Loading in our example and notice what will happen. By default Lazy Loading is enabled in Entity Framework, so just add this line before our code and do the same process.

Notice in SqlProfiler that the query was just One , which means it ignored the Object related Objects

[c].[CategoryID] AS [CategoryID],
[c].[CategoryName] AS [CategoryName],
[c].[Description] AS [Description],
[c].[Picture] AS [Picture]
FROM [dbo].[Categories] AS [c]

Now we are going to use  Include() method and notice what will happen. just change your code to be :

Notice in SqlProfiler that there is just one query looks like :

[Project1].[CategoryID] AS [CategoryID],
[Project1].[CategoryName] AS [CategoryName],
[Project1].[Description] AS [Description],
[Project1].[Picture] AS [Picture],
[Project1].[C1] AS [C1],
[Project1].[ProductID] AS [ProductID],
[Project1].[ProductName] AS [ProductName],
[Project1].[SupplierID] AS [SupplierID],
[Project1].[CategoryID1] AS [CategoryID1],
[Project1].[QuantityPerUnit] AS [QuantityPerUnit],
[Project1].[UnitPrice] AS [UnitPrice],
[Project1].[UnitsInStock] AS [UnitsInStock],
[Project1].[UnitsOnOrder] AS [UnitsOnOrder],
[Project1].[ReorderLevel] AS [ReorderLevel],
[Project1].[Discontinued] AS [Discontinued]
[Limit1].[CategoryID] AS [CategoryID],
[Limit1].[CategoryName] AS [CategoryName],
[Limit1].[Description] AS [Description],
[Limit1].[Picture] AS [Picture],
[Extent2].[ProductID] AS [ProductID],
[Extent2].[ProductName] AS [ProductName],
[Extent2].[SupplierID] AS [SupplierID],
[Extent2].[CategoryID] AS [CategoryID1],
[Extent2].[QuantityPerUnit] AS [QuantityPerUnit],
[Extent2].[UnitPrice] AS [UnitPrice],
[Extent2].[UnitsInStock] AS [UnitsInStock],
[Extent2].[UnitsOnOrder] AS [UnitsOnOrder],
[Extent2].[ReorderLevel] AS [ReorderLevel],
[Extent2].[Discontinued] AS [Discontinued],
FROM   (SELECT TOP (3) [c].[CategoryID] AS [CategoryID], [c].[CategoryName] AS [CategoryName], [c].[Description] AS [Description], [c].[Picture] AS [Picture]
FROM [dbo].[Categories] AS [c] ) AS [Limit1]
LEFT OUTER JOIN [dbo].[Products] AS [Extent2] ON [Limit1].[CategoryID] = [Extent2].[CategoryID]
)  AS [Project1]
ORDER BY [Project1].[CategoryID] ASC, [Project1].[C1] ASC

This query shows the Object Category and its related Objects Projects in One query.

Finally we will try the Explicit Loading , just change your code to be like this :

Notice in SqlProfiler it looks like the Lazy Loading result , there are 4 queries to the database.

I hope you can differentiate between the three patterns.





Code Sample:


How to authenticate to FaceBook Graph Api – Part III

As I mentioned in the previous post we are going to complete how to connect to facebook graph Api programatically

  1. We are going to create a new web application and name it ConnectToFacebook
  2. In Default.aspx page we are going to but the login to facebook button and a label to show up the accesstoken after successfully login
  3. in code behind we implementing the code to connect to facebook
  4. we are going to explain the code we can begin with LoginToFacebook function
    we have to make sure that the user is authorized before getting access token if not so redirect user to authorize the application from facebook. After user authorize the application to access via facebook login page then facebook returned to the application via the return url which we specefied in the authorization url with code as a querystring

    so in page load i make a check on code querystring to make sure if the user loading the page after authorization or not if code querystring is exist so we can call GetAccessTokenFromRequest function,in this function we are going to connect to facebook by reading the stream of httpreqest to facebook and get accestoken and accesstoken time from the request.
  5. I usually store information about my api in web.config to be easy to change in the future if i want to do that, so i used

    to get facebook application id and application secret from web.config that keys which facebook generate after creating a new application as we described in a previous posts also there is scope users only grant your app access to their basic information. If you want to read additional data or write data to Facebook, you need to request additional permissions. In the various authentication flows, you should specify the additional permissions you require using the Scope parameter. so i put it in web.config to
  6. here is an example of web.config

    as we can see in the code sample I used HttpWebRequest and StreamReader to get data from facebook

You can download the sample from here ConnectToFacebook

Setup WordPress Using WebPlatform for Windows

1-    Go to  http://www.microsoft.com/web/wordpress website and click on install WordPress as in figure (1.0)

Figure (1.0)

2- Web Platform will open after click install to guide you throw setup steps as in figure (1.1)

Figure (1.1)

3- Web platform will ask you to download MySql on your machine or as a remote server as figure (1.2)
Figure (1.2)

4- Accept to download third party , application and components and Microsoft software to continue MySql install as figure(1.3)

Figure (1.3)

5- Next enter password for your database as in figure (1.4)

Figure (1.4)

6- Install MySql will start progress as  in figure (1.5)

Figure (1.5)


7- Next create new database or use existing one,note that database password can’t be empty as  in figure(1.6)


8- last step after downloading will congratulate you about download WordPress MySql and other products as in figure (1.7)

Figure (1.7)

9- Now you should have the Microsoft WebMatrix on your machine ready to use,open it and click on My Sites as  in figure (1.8)

Figure (1.8)

10- After click on My Sites click on WordPress and then OK button, will open a new window from there click on run you will find it at the top of your screen as  in figure(1.9)


11- Now WordPress will  Guide you through your Personal platform information(This Step will open on your browser as web page),Note that the Site Title field will be your blog name, After finish filling your information click on install WordPress button as  in figure(2.0)


12- Now you should see the success step and it’s ready to Login as  in figure(2.1)


13-  After Login it will guide you through your dashboard page, From there click on New then post to start your first blog post as  in figure(2.2)


14- In the add new post page there are many options helps you to start your first post, there is a field to write your post title and under it you can find an Upload/Insert link to help you insert audio or video on your post, on the right you can see three important buttons(save Draft.Preview and Publish) save Draft help you to save your post without publishing for all users online so you back edit or change it, preview help you to see your blog before publish, then if you click publish that means that your blog will be seen online for every one as in figure(2.3)


15- Now you can go to All Posts in you dashboard menu and you will find the posts you save to drafts or publish with info about its date and last modified if draft as  in figure(2.4)


This setup steps done using the following:

* Windows 7 Ultimate
* WordPress 3.3.1
* Web Platform 7.1.1070.1
* WebMatrix 7.1.1073.1