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 am using Automapper and NHibernate. In NHibernate, the DictionaryRecord property is marked as lazy loaded .

When I make the comparison by DictionaryEntityDictionaryDto , AutoMapper loads all my vocabulary dictionaries.

But I don't want this behavior, there is a way to configure Automapper to not allow this property until I actually have access to that property.

My workaround for this situation consists of splitting the dictionary into 2 classes and creating 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 code, call AutoMapper.Map as appropriate.

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

      

Does anyone have a better solution for my problem?

+3


source to share


2 answers


You have to add a condition to check if the collection is initialized for the mapping. You can read more details here: Automapper: ignore provided .



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

      

+3


source


Is it okay to ignore the property if it's helpful?

AutoMapper.Mapper.CreateMap<DictionaryEntity, DictionaryDto>()
    .ForMember(dest => dest.DictionaryRecord,
               opts => opts.Ignore());

      



http://cpratt.co/using-automapper-mapping-instances/

0


source







All Articles