c# - Automapper 和 NHibernate : lazy loading

标签 c# nhibernate fluent-nhibernate automapper

我有以下场景。

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/

相关文章:

c# - 多个线程访问一个返回方法,带锁是线程安全的吗?

c# - 实用类..好还是坏?

nhibernate - 我在这个模型中打破了我的聚合边界吗?

mysql - 外部右连接在 NHibernate 中不起作用

c# - Fluent nHibernate 中的嵌套查询

azure - 无法在 Azure 移动服务上找到程序集

c# - 在 C# 中调用 super 构造函数

c# - 我在哪里可以得到 NLog 提供的 "ambient properties"的列表?

sql-server-2008 - NHibernate : Store VARBINARY to MAX

nhibernate - 针对特定场景(一对多/一对一)更正 NHibernate 映射