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?

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

4 Comments

What is the parent tag?
Just optional.. just a way how NHibernate could give your collection items BACK reference to collection holder/parent. Cool and sexy feature ;)
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.
NO. (sorry) Check the doc 7.2. Collections of dependent objects: "Composite elements may contain components but not collections" But, regardless this small NO, enjoy mighty NHibernate ;) it is amazing tool

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.