【问题标题】:How do I set the Fetchmode on all assocations of a nHibernate ICriteria in one go?如何一次性在 nHibernate ICriteria 的所有关联上设置 Fetchmode?
【发布时间】:2009-12-23 08:15:48
【问题描述】:

我有一个与其他对象有很多关联的对象。所有这些都是由 nHibernate 懒惰地获取的,这在几乎所有情况下都很好。

在特定情况下,在这种情况下导出大量记录,我想将 Fetchmode 设置为对所有关联进行渴望。有没有办法做到这一点,而不必手动指定每个:

ICriteria crit = CreateCriteria().
  .SetFetchMode("Address", FetchMode.Eager)
  .SetFetchMode("ContactPerson", FetchMode.Eager);

我想找到但没能找到的方法:

// This doesn't work.
ICriteria crit = CreateCriteria().SetFetchMode(FetchMode.Eager);

【问题讨论】:

    标签: .net nhibernate criteria eager-loading


    【解决方案1】:

    您可以尝试使用 NHibernate 元数据。

    ISessionFactory sessionFactory;
    
    Type type = typeof(MyEntity);
    IClassMetadata meta = sessionFactory.GetClassMetadata(type);
    foreach (string mappedPropertyName in meta.PropertyNames)
    {
        IType propertyType = meta.GetPropertyType(mappedPropertyName);
        if (propertyType.IsAssociationType)
        {
          // initialize property
          // recursively go through the properties of the associated entity
        }
    
        if (propertyType.IsCollectionType)
        {
          // initialize collection
          // if it is a collection of entities, 
          // recursively go through the properties of the associated entity
    
          // Use NHibernateUtil.Initialize
        }
    }
    

    我不确定这是否值得。

    【讨论】:

    • 谢谢。我在无法访问 sessionfactory 的级别执行操作,所以我怀疑这种方法对我有什么好处。但我会研究元数据!
    • 你可以在你知道会话工厂的地方实现这整个东西,并通过一个接口提供给另一部分。
    【解决方案2】:

    不,没有办法以一揽子方式做到这一点。

    【讨论】:

    • 唉...这是事实。我使用了一种不同的方法,逐个获取记录并附加到导出中,并在两者之间刷新会话。现在,服务器不再内存不足。这至少是我们为发布版本而实施的快速修复:P
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多