Tuesday, August 21, 2012

LazyLoading in Entity Framework 4


LazyLoading in Entity Framework 4:-


1.  By default Lazy Loading is Enable in Entity Framework. When we are using EF and have       performance issues with their applications this is because number of queries that hit the database to return the data when lazy loading is enables.

Suppose if we have table country,state and city and we run this code on page load :-

      using(var ctx = new CompanyEmployeesEntities())        

{         
            
var query = testContext.tbCountries.Take(5);

            
foreach (var country in query)
            {
                Response.Write(
country.countryName);

                Response.Write(
"<br/>");

                
foreach (var State in country.tbStates)

                {
                    Response.Write(
State.StateName);
                    Response.Write(
"<br/>");
                }
            }

        }

Run your application and you will see that we get the country names and their associated State  names.in this multiple query are fired and compare country with states associated with it. This will cause  performance issues with in their applications.

2.     Turn-off Lazy Loading
We can turn off the lazy loading feature and fetch the related records in one query itself. This   process is termed as eager loading. To turn off Lazy Loading we can set LazyLoadingEnabledproperty of the ContextOptions on context to false.
      ctx.ContextOptions.LazyLoadingEnabled = false;
Now if we run the earlier code, we get the country names from table tbCountries. This is because only the first query is executed. Only You will not see the related entities (countryName) displayed on the screen
It is nice to have options. Use them carefully depending on the specific requirements of your application. 







No comments:

Post a Comment