How can i map a computed list property in nhibernate

56 Views Asked by At

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

2

There are 2 best solutions below

0
On BEST ANSWER

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.

0
On

Well, the answer did in fact NOT work but i figured it out:

<bag name="Values" lazy="false" access="property" mutable="false">
<subselect>
SELECT p.Value as id, p.PRODUCTID FROM PRODUCTS p where p.PRODUCTID = ProductId
</subselect>
<key column="ProductId"/>
<element type="double"/>
</bag>

The reason I select the value as id, and the productId is because of the weird query nhibernate generated where it would select and id and productId because of the foreign key. I dont really understand the generated query but i transformed my custom query to this format.

This seems like a hack but works for now, i still do not know how to simply query a list of results and use it as a computed property for my models.