NHibernate Caching Objects Based on Parent Class's ID

痞子三分冷 提交于 2019-12-11 05:32:55

问题


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?


回答1:


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.




回答2:


With respect, the question you should be asking is "how do I model this correctly?"

Your Dogs table says that dog 10 is owned by owner 1 and is strong, but, at the same time, dog 10 is owned by owner 2 and is NOT strong.

Somehow, I don't think that's what you meant.

If you'll explain in more detail what you're trying to model, perhaps we can make some suggestions.




回答3:


Make AnimalID and OwnerID a composite primary key.



来源:https://stackoverflow.com/questions/1849195/nhibernate-caching-objects-based-on-parent-classs-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!