开发者

NHibernate: many-to-one relationships using pre-loaded references

I'm using a many-to-one relationship as follows:

Classes:

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; }
}

Mappings:

  <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>

This is working fine, with a lazy read on the Account property of an instance of AnotherClass.

However, due the application I'm working in, there will be many instances of AnotherClass, with a high throughput. There will only be a handful of Accounts though. The Accounts are already cached in memory in a List. I can guarantee that the Accounts list in memory matches that in the database.

Rather than the lazy read hitting the database for account details I want to intercept the either the population of the object or the lazy read and reference the right item in the cached accounts list. This gives two advantages - much fewer selects, and any changes to the accounts will automatically be reflected in instances of AnotherClass as they'll all reference the same instance of the Account.

Because of the lazy read, I can access the AnotherClass.Account.AccountID property without incurring the extra select. Hopefully that'll provide a way in.

I still want the adds/updates/removes on the AnotherClass object to update the AccountID property.

So the question is: How might I go about filling the Account property with details from the cached list instead of the database, based on the AccountID from the AnotherClass table?


Since the Account you have cached belongs to another session I think you can create an interceptor ( look at here: http://weblogs.asp.net/srkirkland/archive/2009/09/03/simple-auditing-using-an-nhibernate-iinterceptor-part-2.aspx ) and when an object is loaded that needs an Account you can lock the reference to the current session and assign it to the property. A less intrusive way can be implement yourself ( or use an existing ) second level cache.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜