1

Is possible to map a raw sql to an entity with NHibernate?

Like the following:

C# entity:

public virtual IList<Result> MyResult { get; set; }

Hbm.xml:

<bag name="MyResult">
    <my-custom-sql type="Result">
        SELECT * FROM ResultTable where MyComplexCondition = true
    </my-custom-sql>
</bag>

Result has it own hbm.xml. Is possible to do what I want to achieve?

Radim Köhler
  • 122,561
  • 47
  • 239
  • 335
Arthur Castro
  • 610
  • 6
  • 18

1 Answers1

1

There is a feature, called <subselect>. See more here

How to map an NHibernate entity to a query

That could be applied on <class> as well as on <bag>. This could be the way how to use it on a bag for MyEntity which has collection of Languages 

<bag name="Languages" lazy="true" batch-size="25" 
     mutable="false" >
  <subselect>
    SELECT MyEntity_ID, Language_ID, IsNative FROM Languages
  </subselect>
  <key column="MyEntity_ID" />
  <composite-element class="Language">
    <parent name="MyEntity"/>
    <many-to-one not-null="true" name="Language" class="Language" column="Language_ID" />
    <property not-null="true" name="IsNative" column="IsNative"/>
  </composite-element>
</bag>

This of course, should be used for readonly (immutable) solutions

Community
  • 1
  • 1
Radim Köhler
  • 122,561
  • 47
  • 239
  • 335
  • What is the parent tag? – Arthur Castro Nov 03 '15 at 13:26
  • Just optional.. just a way how NHibernate could give your collection items *BACK reference* to collection holder/parent. Cool and sexy feature ;) – Radim Köhler Nov 03 '15 at 13:27
  • One last question (it's really hard to find someone who understand this aspect of NHibernate): Can I map some collection inside a composite-element tag? A bag, for example, that have a key pointing to an Id property of the composite-element. – Arthur Castro Nov 03 '15 at 16:23
  • 1
    NO. (sorry) Check the doc [7.2. Collections of dependent objects](http://nhibernate.info/doc/nhibernate-reference/components.html#components-incollections): *"Composite elements may contain components but not collections"* But, regardless this small NO, enjoy mighty NHibernate ;) it is amazing tool – Radim Köhler Nov 03 '15 at 16:34