Paul T Davies
Paul T Davies

Reputation: 2573

NHibernate - mapping a collection based on a different property to the identity

Consider the following tables:

Client(Id bigint, Name varchar(50))
Employee(Id bigint, Name varchar(50), ClientId bigint)

that are mapped like this:

<class name="Client" table="`Client`">
  <id name="Id" column="`Id`" type="long">
    <generator class="native" />
  </id>
  <property name="Name" column="`Name`" />
  <bag name="Employees" cascade="all" inverse="true" >
    <key column="`ClientId`" />
    <one-to-many class="Employee" />
  </bag>
</class>

<class name="Employee" table="`Employee`">
  <id name="Id" column="`Id`" type="long">
    <generator class="native" />
  </id>
  <property name="Name" column="`Name`" />
  <many-to-one name="Client" cascade="all" column="`ClientId`" />
</class>

If I get a Client, I also get a collection of Employees where the Employee.Client = Client.Id. Great.

Now consider this:

Client(Id bigint, Name varchar(50), AlternativeId int)
Employee(Id bigint, Name varchar(50), ClientId bigint, AlternativeClientId int)

I want to return a Client with a collection of Employees where Employee.AlternativeClientId = Client.AlternativeId.

I would assume the key node would now read:

<key column="`AlternativeClientId`"/>

But beyond that I'm stumped. There are filters that can be applied to collections, but the set of Employees in the second version may not be a subset of the Employees in the first version, so I don't think that is the way forward. I tried but that seemed to be a dead end. IS there some way of specifying a query, but not only on Employees that have the ClientId = Client.Id?

(For the 'whys': It's to do with how different systems have different views of the data.)

Upvotes: 0

Views: 958

Answers (1)

Peadar Doyle
Peadar Doyle

Reputation: 1112

I'm pretty new to nhibernate but this sounds like a problem I had due to working with a brownfield database. The property-ref attribute allows a column other than the primary key to be referenced. So in your case it should be:

    <key column="AlternativeClientId" property-ref="AlternativeId"/>

Upvotes: 2

Related Questions