Lazy Loading Association and Casting

Posted by Zuber on Stack Overflow See other posts from Stack Overflow or by Zuber
Published on 2010-03-19T07:33:22Z Indexed on 2010/03/19 9:01 UTC
Read the original article Hit count: 497

Filed under:
|

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.

© Stack Overflow or respective owner

Related posts about nhibernate

Related posts about lazy-loading