Search code examples
c#nhibernatecachingjoined-subclasssession-cache

NHibernate Caching Objects Based on Parent Class's ID


I have the following definitions for the Animal and Dog types. Note that the ID for the object is the AnimalID:

<class name="Animal" table="Animals">
    <id name="Id" type="System.Int32" column="AnimalID">
        <generator class="identity" />
    </id>
    <property name="IsBig" column="IsBig" type="System.Bool" not-null="true" />  
</class>

<joined-subclass name="Dog" table="Dogs" extends="Animal">
    <key column="AnimalID" />
    <property name="OwnerID" column="OwnerID" type="System.Int32" non-null="true" />
    <property name="IsStrong" column="IsStrong" type="System.Bool" non-null="true" />
</joined-subclass>

Let's say I have the following information in my database:

in table Animals:

AnimalID    IsBig
--------    -----
10          True

in table Dogs:

AnimalID    OwnerID    IsStrong
--------    -------    --------
10          1          True
10          2          False

First, I query for the Dog where OwnerID = 1. In the same session, I query for the Dog where OwnerID = 2. Because of NHibernate's Session cache, the second query returns a Dog object where OwnerID = 1 and IsStrong = True, where it should return a Dog object where OwnerID = 2 and IsStrong = False.

NHibernate automatically caches objects by their ID (primary key) column, so requesting the Dog the second time ends up retrieving an object with the same key. I can solve this problem by calling ISession.Evict() on the object, but that seems like a hack.

Any better suggestions?


Solution

  • You must ensure you're using different keys for different instances. In your case you're actually violating this rule: Dogs table exposes parts of two instances sharing the same key.

    So Dogs.AnimalID must be marked as primary key, but in your case it isn't. If it would be marked as PK, you couldn't get such content at all.