Sep
21
2006
Lazy loading of structures in C# - howto part 8
Posted by admin under
In practice
Now, in this part of the "In practice" serie - lets look even deeper into lazy loading.
In our project we have two distinct types - Customer and File - and we do have a clear relation between them. One file is owned by one single customer. One single customer can be associated to many files.
So, our C# class hierarchy should probably reflect that, don't you think. We have already created classes and collections - so it's easy to add a FileCollection to our customer object:
public class Customer
{
FileCollection m_oFiles = null;
public FileCollection Files
{
get
{
if (m_oFiles == null)
{
m_oFiles = new FileCollection();
m_oFiles.OpenForCustomer(Id);
}
return m_oFiles;
}
}
Notice how we lazy load the Files collection - in the beginning it's null - but first time the Property Files is accessed it will be created - and we call OpenForCustomer - sending in the Id for the current customer object.
This makes our old code in editcust.aspx a lot easier to use:
old code:
CustomerClasses.Customer oCustomer = GetCustomer();
if (oCustomer == null)
{
header.InnerText = "New customer";
}
else
{
header.InnerText = "Edit customer";
txtName.Text = oCustomer.Custname;
//Setup repeater existing
CustomerClasses.FileCollection oColl = new CustomerClasses.FileCollection();
oColl.OpenForCustomer(oCustomer.Id);
rptExistingFiles.DataSource = oColl;
rptExistingFiles.DataBind();
new code:
CustomerClasses.Customer oCustomer = GetCustomer();
if (oCustomer == null)
{
header.InnerText = "New customer";
}
else
{
header.InnerText = "Edit customer";
txtName.Text = oCustomer.Custname;
//Setup repeater existing
rptExistingFiles.DataSource = oCustomer.Files;
rptExistingFiles.DataBind();
}