C# Automapper和NHibernate:延迟加载

C# Automapper和NHibernate:延迟加载,c#,nhibernate,fluent-nhibernate,automapper,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 {

我有下面的场景

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; }
}
公共类字典实体
{
公共虚拟字符串字典名称{get;set;}
公共虚拟IList字典记录{get;set;}
}
公共类字典
{
公共字符串字典名称{get;set;}
公共IList字典记录{get;set;}
}
我用的是Automapper和NHibernate。在NHibernate中,字典记录属性标记为延迟加载

当我从DictionaryEntity->DictionaryTo进行映射时,Automapper会加载我所有的DictionaryRecords

但我不希望出现这种行为,有没有办法配置自动映射程序,以便在我真正访问该属性之前不解析该属性

我的解决方法是将DictionaryEntity拆分为2个类,并创建第二个Automapper映射

public class DictionaryDto
{
     public string DictionaryName { get; set; }
}

public class DictionaryDtoFull : DictionaryDto
{
     public IList<DictionaryRecordEntity> DictionaryRecord { get; set; }
}
公共类字典
{
公共字符串字典名称{get;set;}
}
公共类DictionaryDtoFull:DictionaryDto
{
公共IList字典记录{get;set;}
}
然后在代码中,根据需要,适当地调用AutoMapper.Map

return Mapper.Map<DictionaryDto>(dict);            
return Mapper.Map<DictionaryDtoFull>(dict);
返回Mapper.Map(dict);
返回Mapper.Map(dict);

有人能为我的问题提供更好的解决方案吗?

如果这有用的话,您可以忽略该属性

AutoMapper.Mapper.CreateMap<DictionaryEntity, DictionaryDto>()
    .ForMember(dest => dest.DictionaryRecord,
               opts => opts.Ignore());
AutoMapper.Mapper.CreateMap()
.FormMember(dest=>dest.DictionaryRecord,
opts=>opts.Ignore());

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

AutoMapper.Mapper.CreateMap()
.FormMember(dest=>dest.DictionaryRecord,opt=>opt.Premission(source=>
NHibernateUtil.已初始化(来源:DictionaryRecord));

感谢您的快速回复。我觉得那对我没用。在这种情况下,DictionaryRecord列表将是空的,对吗?您可能是对的,尽管您可能有两个方法—一个包含上述代码,忽略一个,另一个加载所有属性。我不确定AutoMapper是否能满足您的要求。虽然这不是我想要的,但我认为这是可能的最佳解决方案。Thanks@Najera你确定这是正确的吗?据我所知,条件发生在映射之后,应该使用前提条件。看到了吗(或者可能是正确的,但是automapper的情况已经发生了变化?@Adam你是对的,我记得我做了一个测试,它在几个项目中都起了作用,但是在上一个版本中,
predition
是正确的方法。谢谢
AutoMapper.Mapper.CreateMap<DictionaryEntity, DictionaryDto>()
    .ForMember(dest => dest.DictionaryRecord, opt => opt.PreCondition(source =>
        NHibernateUtil.IsInitialized(source.DictionaryRecord)));