【问题标题】:NHibernate: many-to-one relationships using pre-loaded referencesNHibernate:使用预加载引用的多对一关系
【发布时间】:2023-03-26 07:46:01
【问题描述】:

我使用的多对一关系如下:

类:

public class Account
{
    public virtual long AccoungID { get; set; }
    public virtual string UserName { get; set; }
}

public class AnotherClass
{
    public virtual long AClassID { get; set; }
    public virtual Account Account { get; set; }
}

映射:

  <class name="Account">
    <id name="AccountID">
      <generator class="hilo"/>
    </id>
    <property name="Username"/>
  </class>  

  <class name="AnotherClass">
    <id name="AnotherClassID">
      <generator class="hilo"/>
    </id>
    <many-to-one name="Account" class="Account" column="AccountID"/>
  </class>

这工作正常,对 AnotherClass 实例的 Account 属性进行了延迟读取。

但是,由于我正在使用的应用程序,将有许多具有高吞吐量的 AnotherClass 实例。不过,只有少数几个帐户。帐户已缓存在列表中的内存中。我可以保证内存中的 Accounts 列表与数据库中的一致。

我想拦截对象的填充或延迟读取并在缓存的帐户列表中引用正确的项目,而不是通过延迟读取访问数据库以获取帐户详细信息。这有两个优点 - 更少的选择,并且对帐户的任何更改都将自动反映在 AnotherClass 的实例中,因为它们都将引用相同的 Account 实例。

由于延迟读取,我可以访问 AnotherClass.Account.AccountID 属性而不会产生额外的选择。希望这将提供一种方式。

我仍然希望 AnotherClass 对象上的添加/更新/删除来更新 AccountID 属性。

所以问题是:我如何才能根据 AnotherClass 表中的 AccountID 使用缓存列表而不是数据库中的详细信息填充 Account 属性?

【问题讨论】:

    标签: c# nhibernate


    【解决方案1】:

    由于您缓存的帐户属于另一个会话,我认为您可以创建一个拦截器(请看这里:http://weblogs.asp.net/srkirkland/archive/2009/09/03/simple-auditing-using-an-nhibernate-iinterceptor-part-2.aspx),当加载需要帐户的对象时,您可以锁定引用当前会话并将其分配给属性。一种侵入性较小的方式可以自己实现(或使用现有的)二级缓存。

    【讨论】:

      猜你喜欢
      • 2020-08-13
      • 1970-01-01
      • 2023-03-23
      • 1970-01-01
      • 2013-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多