'Include primary key of reference table in model using NHibernate
We are using NHibernate for DB operations and in our database there is a reference of Organisation in the Configuration table. This is existing code and cannot be changed.
Configuration table is heavily used throughout application so we want to include the OrganisationId in the Configuration model class, but not in table as it already has reference object. By doing this we will avoid loading whole organisation object when we just need OrganisationId.
//Configuration.hbm.xml
<many-to-one name="Organisation"
class="Organisation"
not-null="false"
foreign-key="FK_ConfigurationItem_Organisation"
unique-key="UniqueConfigurationItemName"/>
//Configuration.cs (Model Class)
public virtual Organisation Organisation { get; set; }
How do I modify hbm or model class so that we get organisationId without including this field in table?
I am new to NHibernate and stuck with this requirement.
Any suggestion will be appreciated. Thanks
Solution 1:[1]
it should not be necessary to try this optimization manually, because NHibernate has multiple options to handle that on it's own, and that methods work especially well for heavily used object (aka. rows). If you use a session-object with a cache NHibernate will prefere to access the cache (aka. memory) and not load from the database (a second, third or ... time). If you use eager or join-loading then NHibernate will include simple foreigen keys in the first sql to the database, a much quicker way then lazy-loading (only bad if he foreigen key is never accessed).
BUT
This is a bit of a guess and I am not 100% sure that it is the intended way to do it, but I accidentally mapped a column twice and you could do that too for the organisation, once as a foreigen key and once as a simple column (of witch ever type organisationid is). Make sure that the setter of the "simple column" property is not public! Make sure to update the "simple column" in the setter of the foreign key.
Greetings
Juy Juka
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Juy Juka |
