Automapper和NHibernate:延迟加载

3

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; }
}

我正在使用Automapper和NHibernate。在NHibernate中,DictionaryRecord属性被标记为延迟加载
当我从DictionaryEntity映射到DictionaryDto时,Automapper会加载所有的DictionaryRecords。
但我不想要这种行为,有没有一种方式可以配置Automapper以在我真正访问该属性之前不解析此属性
我针对这种情况的解决方法是将DictionaryEntity拆分为两个类并创建第二个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);

有没有更好的解决方案来解决我的问题?

2个回答

3

您必须添加一个条件来验证集合是否已初始化为映射。您可以在此处阅读更多详细信息:Automapper:根据条件忽略

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

虽然这不完全是我想要的,但我认为这是最好的可能性解决方案。谢谢 - Mischa
1
@Najera,你确定这是正确的吗?据我所知,条件发生在映射之后,应该使用PreCondition。请参见https://dev59.com/FFkR5IYBdhLWcg3w6RMD(或者也许它是正确的,但是随着自动映射器的变化,事情已经改变了?) - Adam
@Adam 你说得对,我记得我曾经测试过并且在几个项目中都能正常工作,但是PreCondition是最新版本中正确的方法。谢谢。 - Najera

0

感谢您的快速回复。我认为这对我没有用。在这种情况下,DictionaryRecord列表将会是空的,对吗? - Mischa
你可能是对的,虽然你可以有两种方法,一种是具有上述代码并忽略其中一个,另一种是以惰性方式加载所有属性。我不确定AutoMapper能否做到你所要求的。 - nik0lai

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接