【问题标题】:Dealing with lazy loading outside of an ISession?处理 ISession 之外的延迟加载?
【发布时间】:2012-05-03 18:16:44
【问题描述】:

我正在使用 NHibernate 在我的应用程序中进行数据库访问。我的ISessions 没有持久性,我对此很满意,因为它使我更容易将我的应用程序分成不同的层。唯一的困难是以一种很好的方式处理延迟加载。

我有一个看起来像这样的模型类:

public class User {
    public virtual int Id { get; set; }
    public virtual string Name { get; set; }
    public virtual Country CountryOfBirth { get; set }
    public virtual Country CountryOfResidence {get; set; }
}

目前,我将CountryOfBirthCountryOfResidence 设置为fetch="join"。但是,由于我的数据库中的国家列表大部分是静态的,我想缓存这些值。我将CountryOfBirth 属性更改为如下所示:

    Country countryOfBirth;
    public virtual Country CountryOfBirth{
        get
        {
            if (country is INHibernateProxy)
                countryOfBirth = CountryRepository.GetById(countryOfBirth.Id);
            return countryOfBirth;
        }
        set { countryOfBirth = value; }
    }

但是,它需要我的 Model 类知道 NHibernate 正在使用它,这会破坏封装。

有没有更好的方法来实现这一点?例如,如果 NHibernate 尝试加载代理并且会话已过期,是否有办法让 NHibernate 自动通过我的 Repository 类?

或者我应该使用其他方法吗?

【问题讨论】:

    标签: c# nhibernate


    【解决方案1】:

    如果您想添加缓存功能,请查看 NHibernate L2 缓存。查看本教程http://nhforge.org/blogs/nhibernate/archive/2009/02/09/quickly-setting-up-and-using-nhibernate-s-second-level-cache.aspx 并搜索此主题。通过使用缓存,您不会使用任何 NH 代理、存储库等来污染您的模型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多