Entity Framework: Concepts and headaches. Lazy Loading

So when I wrote this and this I didn’t really have a precursor to some of the concepts in the posts so I figured I’d get them out of the way now since I’ll be posting a bunch on the Entity Framework.

First off is lazy loading. Now I could put the obligatory stupid joke here that gives some kind of novel, but incorrect, explanation of the phrase (Like say making someone else wash your clothes) but I so much better than that. So what is lazy loading? Simply put it’s not getting something until you need it. Kind of like “If it ain’t broke then don’t fix it” instead you trade “broke” with “needed” and “fix” with “get”. So it’s really not like that phrase. It is however, when talking about objects being hydrated (ie loaded) from some kind of storage (ie database) in a program written by some idiot. (ie me) Let’s say you have a User table and a Site table in which there are many Users to one Site. Now with an ORM this will be represented by an User object, a Site object, and a property on User that is of type Site. It would look something like this:

    public class User
    {
      private Site _site = null;

      public Site ParentSite
      {
         get
         {
            if(_site == null)
            {
               _site = SomeMethodToGetSite();
            }

            return _site;
         }
      }
    }

When you load the User from storage, initially the Site object on the User object is null. This is done because if you don’t need the Site yet, why take up space until you do? This is the concept of lazy loading. Now in most ORMs, the Site would automatically be hydrated the first time the Site property was accessed. Entity Framework is slightly more complicated when dealing with the many to many or one to many situation.

This happens when you have a Users list on the Site object that basically represents every User in the User table that has the same SiteID as the Site in question. OR maybe you have a hanging table UserSite that allows for one Site to have many Users and one User to have many Sites. Either way, you will be left with a collection that represents this relationship. (Users list on the Site object) Now say you do this:

  Site someSite = LoadSiteByID(siteID);

and then you try to do this:

  someGrid.DataSource = someSite.Users;
  someGrid.DataBind();

When the page loads, there are no records in the grid. In a normal ORM this wouldn’t be a problem. It would see that you are accessing the .Users property and hit the database to fill the list. Entity Framework requires you to take one more step in this case.

  someGrid.DataSource = someSite.Users.Load();

Not that big of a deal. Now there is a check even to see if it is loaded in the first place:

  order.Users.IsLoaded

This is a boolean property that says true when it has been loaded. Next post I’ll hit on what happens when you query and how that relates to this situation.