我有以下场景。
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 映射。
public class DictionaryDto
{
public string DictionaryName { get; set; }
}
public class DictionaryDtoFull : DictionaryDto
{
public IList<DictionaryRecordEntity> DictionaryRecord { get; set; }
}
然后在代码中,根据需要,适当调用AutoMapper.Map。
return Mapper.Map<DictionaryDto>(dict);
return Mapper.Map<DictionaryDtoFull>(dict);
有人对我的问题有更好的解决方案吗?
最佳答案
您必须添加一个条件来验证集合是否初始化为映射。您可以在此处阅读更多详细信息:Automapper: Ignore on condition of .
AutoMapper.Mapper.CreateMap<DictionaryEntity, DictionaryDto>()
.ForMember(dest => dest.DictionaryRecord, opt => opt.PreCondition(source =>
NHibernateUtil.IsInitialized(source.DictionaryRecord)));
关于c# - Automapper 和 NHibernate : lazy loading,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30169019/