views:

24

answers:

1

How would one implement lazy loading in the context of three tiers? I understand the basic architecture of Presentation Layer, Business Layer, and Data Layer:

You have your basic "dumb" classes that are nearly mirror images of the tables in the database with one exception. Instead of foreign key IDs you have a reference to the actual instance(s) of what is being referred to. For example: Employee with Name/DOB/Title properties.

Then for each of these classes you have a class that provides the CRUD operations on it plus any custom data storage routines you might need (calling a stored procedure that works with that object, etc). This class would be swapped out if you changed database. For example: EmployeeDAL.Save(myEmployee), EmployeeDAL.Get(myEmployee) (where myEmployee has their ID populated but nothing else)

You have business layer classes that perform validation and what not. The methods in these classes usually end by calling into the DAL to persist information or to retrieve it. This is changed when the customer changes their mind about what constitutes valid/invalid data or wants to change the way some calculation is done.

The presentation layer interacts with the business layer to display things and shuttle inserts/updates made in the UI to the lower layers. For example: it loops over a list of Employees and displays them in an HTML table.

But where exactly would the code for lazy loading references go? If the presentation layer has a Company object that it just displayed and is beginning the process of displaying myCompany.Employees, how is that achieved? myCompany is an instance of one of the dumb classes that mirror the database tables and isn't supposed to know about how to retrieve anything.

Do you do as the answer to this question suggests and create a Dummy version of each object? Then the DAL level object can have variables indicating if Employees has or has not been loaded and call DALEmployee.GetEmployees(this)? I feel as if I'm missing something crucial about the pattern...

A: 

If you use a pre-built framework such as nHibernate this will make it all much easier, you can define the lazy-loading in the class/table mapping and when a query is run. To do it yourself in a neat manner is going to take a fair bit of code although the System.Lazy class in .NET 4 may help.

Craig
I'm in a situation where I'm learning a new language and would really rather do everything by hand the first time, just to really "get it". I'm specifically working with php and MySQL but most of my experience is indeed in the .NET world.
colithium