Automapper and NHibernate: lazy loading
我有以下情况。
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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; } } |
我正在使用Automapper和NHibernate。在NHibernate中,DictionaryRecord属性被标记为延迟加载。
当我从DictionaryEntity-> DictionaryDto进行映射时,Automapper会加载我的所有DictionaryRecords。
但是我不希望出现这种情况,有没有一种方法可以配置Automapper以便在我真正访问此属性之前不解析此属性。
在这种情况下,我的解决方法是将DictionaryEntity分成2个类,并创建第二个Automapper映射。
1 2 3 4 5 6 7 8 9 | public class DictionaryDto { public string DictionaryName { get; set; } } public class DictionaryDtoFull : DictionaryDto { public IList<DictionaryRecordEntity> DictionaryRecord { get; set; } } |
,然后根据需要在代码中调用AutoMapper.Map。
1 2 | return Mapper.Map<DictionaryDto>(dict); return Mapper.Map<DictionaryDtoFull>(dict); |
有人对我的问题有更好的解决方案吗?
您必须添加条件以验证集合是否已初始化为要映射。您可以在此处阅读更多详细信息:自动映射器:在以下条件下忽略。
1 2 3 | AutoMapper.Mapper.CreateMap<DictionaryEntity, DictionaryDto>() .ForMember(dest => dest.DictionaryRecord, opt => opt.PreCondition(source => NHibernateUtil.IsInitialized(source.DictionaryRecord))); |
如果有用,您可以忽略该属性?
1 2 3 | AutoMapper.Mapper.CreateMap<DictionaryEntity, DictionaryDto>() .ForMember(dest => dest.DictionaryRecord, opts => opts.Ignore()); |
http://cpratt.co/using-automapper-mapping-instances/