views:

61

answers:

1

So I'm on an NHibernate crash course, and kinda hit a snag with the example below.

Suppose I have the following .NET class:

class A {
    int id;
    int type_var;
    List<B> someCollection;
}

class B {
    int id;
    string someText;
}

I'll probably map it like :

<class name="A" table="A">
    <id name="id" type="Int32">
         <generator type="identity" />
    </id>
    <property name="type_var" />
    <set name="someCollection" table="B">
         <key name="fk_aid" />
         <composite-element class="B">
              <property name="someText" />
         </composite-element>
    </set>
</class>

My problem is, how would you change this mapping if we were only interested in getting those B elements that belong to A (via fk_aid) AND has a type_var value equal to A (let's assume that both A and B have a type_var column, but they're not explicitly related).

I'm thinking that I'll have to work with something like a where clause here?

<set name="someCollection" table="B" where="type_var = type_var">

How exactly would one do this?

A: 

I believe that a sub-select may work in this case (assuming your RDMS supports it); so something like:

<set name="someCollection" table="B" where="type_var = (SELECT A.type_var FROM A WHERE A.fk_aid = id)"> 

I'm not overly clear on what you're trying to achieve here; but you may consider mapping this as a query-only property; as discussed in this article.

DanP
that sounds like it should work, although I can't shake off the feeling that I'd be a bit redundant here. I mean, we've already got an automatic FK link via <key>, but we're doing it again in the query condition. I wonder if NHb has a capacity to avoid this. :)
Richard Neil Ilagan
@Richard; well, in this case you're right - but I don't think it can be avoided because of the way the 'where' clause is created - it more or less assumes you're filtering on the current table.
DanP