Lazy Loading Association and Casting
- by Zuber
I am using NHibernate 2.0.1 and .NET
I am facing issues with Lazy loading an association
I have a BusinessObject class that has associations to other BusinessObject in it, and it can go deeper.
The following function is in the BusinessObject to read the values of a collection in the BusinessObject.
public virtual object GetFieldValue(string fieldName)
{
var fieldItems = fieldName.Split(AppConstants.DotChar);
var objectToRead = this;
for (var i = 0; i < fieldItems.Length - 1; i++)
{
objectToRead = (BusinessObject) objectToRead.GetFieldValue(fieldItems[i]);
}
//if (objectToRead._data == null) return objectToRead.SystemId + " Error: _data was null";
return objectToRead.FieldValue(fieldName.LastItem());
}
The FieldValue function is described below
private object FieldValue(string fieldName)
{
return _data.Contains(fieldName) ? _data[fieldName] : null;
}
The BusinessObject has a dictionary_data which stores the field values.
Assume the fieldName is BusinessDriver.Description and the BusinessObject which has this field is StrategyBusinessDriver
This code breaks down the field name into two - BusinessDriver & Description.
The first iteration reads the BusinessDriver object from StrategyBusinessDriver.
It is cast into a BusinessObject type so that I can call the GetFieldValue again on it to read the next field i.e Description in the BusinessDriver.
The problem is that when I read the BusinessDriver in the first iteration and cast it, I get the Ids and all other details of the BusinessObject but the field dictionary _data and other collections are not fetched. This should be fetched lazily when I read the _data of the BusinessObject.
However, this does not happen and I get an error that _data is null.
Is there something wrongly coded because of which the collection is not fetched lazily?
Please ask for more clarifications if needed.
Thanks in advance.
UPDATE:
It works when I don't do Lazy load.