Microsoft's Entity Framework is a new, powerful tool bringing data modeling, O/RM (object relational mapping) functionality and more. One expected feature of major ORMs is 'Lazy Loading'. Learn how the Entity Framework provides this functionality in a different way. This article will explain the design reasons behind why EF is different than what you would expect, as well as how to achieve the lazy-load functionality you're looking for.
It is important to realize that that ORMs are not a new concept. There are a lot of excellent ORMs out there for Ruby, Python and even for the .Net framework (NHibernate). As a result, when you "jump in" to EF, you may run into an 'issue' similar to what I did (with lazy loading not working the way I thought it would). Because I was used to LINQ to SQL, I was expecting implicit lazy loading, and therefore I thought that EF was broken. This misconception was wrong, and I'll explain more as we go on.
Before I go into detail about the difference in design between the Entity Framework and LINQ to SQL (or other ORMs like NHibernate), I want to show you the code that threw me for a loop. The scenario is simple, I had a "Customers" table and an "Orders" table in my SQL database. I used the LINQ to SQL designer and then the Entity Framework designer (Entity Data Model designer, or EDM). Both designers easily generated my c# code for me that will interact with my database.
My SQL tables had only a few records in there. The "Customers" table had one record, and the "Orders" table had three records that were linked to the customer. So, here's the code I wrote where I initially misjudged EF:
// First, using LINQ to SQL
L2SDataContext linqToSqlContext = new L2SDataContext();
this.MyDataGrid1.DataSource = linqToSqlContext.Customers.First().Orders;
// 3 records in my data grid!!!
this.MyDataGrid1.DataBind();
The above code worked exaclty as I thought it would. The first customer object was recieved from the database, and then when I accessed that customer's orders, LINQ to SQL went back to the database and got the orders. Now, here is what I thought was the same thing using the Entity Framework. Notice how many rows were in my datagrid:
// Using the Entity Framework
EFEntities entityFrameworkContext = new EFEntities();
this.MyDataGrid2.DataSource = entityFrameworkContext.Customers.First().Orders;
// 0 records in my data grid???
this.MyDataGrid2.DataBind();
And that was it. Something so simple as that caused me to spiral into a dark room of confusion. In fact, there are people out there who have 'given up' on EF right there. The problem here is not with the Entity Framework, but with my lack of understanding the underlying design of EF.