C#-Automapper和NHibernate:延迟加载
作者:互联网
我有以下情况.
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)));
标签:automapper,nhibernate,c,fluent-nhibernate 来源: https://codeday.me/bug/20191120/2043209.html