Search code examples
nhibernatemappingcomputed-propertieshbm

How can i map a computed list property in nhibernate


My model contais the following:

public virtual DateTime LastSessionDate { get; set; }
public virtual List<double> Values { get; set; }

Values should be selected from other tables in a custom sql query, but I am failing to map Values in the hbm.xml file.

<property name="LastSessionDate" formula="(select ...)" />

works great, but how do i map the list?

Ive already tried many combinations of <bag> and <subselect>, but cannot get it to work.

<many-to-one name="Values" access="readonly">
   <formula>(select ...)</formula>
</many-to-one>

leads to NHibernate.MappingException: persistent class not known: System.Collections.Generic.List`1[[System.Double]

Any Ideas? The nhibernate documentation did not help me with this


Solution

  • Use bag to map a collection:

    <bag name="Values" lazy="true" access="property" mutable="false">
       <subselect>
          SELECT value_column_name FROM some_table WHERE some_conditions
       </subselect>
       <key column="foreign_key_column_name"/>
       <element type="double"/>
    </bag>
    

    lazy="true" makes so SQL won't be executed until you access the collection.

    access="property" is necessary since your property is virtual and will likely be proxied by NHibernate.

    mutable="false" indicates that the collection is read-only and shouldn't be changed.