Search code examples
c#nhibernatefluent-nhibernateautomapper

Automapper and NHibernate: lazy loading


I have the following scenario.

public class DictionaryEntity
{
    public virtual string DictionaryName { get; set; }

    public virtual IList<DictionaryRecordEntity> DictionaryRecord { get; set; }
}

public class DictionaryDto
{
     public string DictionaryName { get; set; }

     public IList<DictionaryRecordEntity> DictionaryRecord { get; set; }
}

I'm using Automapper and NHibernate. In NHibernate the DictionaryRecord property is marked as lazy loaded.

When I make the mapping from DictionaryEntity -> DictionaryDto, Automapper loads all my DictionaryRecords.

But I don't want this behavior, is there a way to configure the Automapper in order to don't resolve this property until I really access this property.

My workaround for this situation consists of splitting the DictionaryEntity in 2 classes and create a second Automapper mapping.

public class DictionaryDto
{
     public string DictionaryName { get; set; }
}

public class DictionaryDtoFull : DictionaryDto
{
     public IList<DictionaryRecordEntity> DictionaryRecord { get; set; }
}

and then in the code, depending on the need, call AutoMapper.Map appropriately.

return Mapper.Map<DictionaryDto>(dict);            
return Mapper.Map<DictionaryDtoFull>(dict);

Does somebody have a better solution for my problem?


Solution

  • You must add a condition to validate if the collection is initialized to be mapped. You can read here more details: Automapper: Ignore on condition of.

    AutoMapper.Mapper.CreateMap<DictionaryEntity, DictionaryDto>()
        .ForMember(dest => dest.DictionaryRecord, opt => opt.PreCondition(source =>
            NHibernateUtil.IsInitialized(source.DictionaryRecord)));