Search code examples
c#nhibernatenhibernate-mappinghbm

Mapping native sql to Entity with NHibernate


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?


Solution

  • 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