Suppose I have the following tables:
Company Person Address
----------------------------------------------------------------------------
Id (PK) Id (PK) Id (PK)
Name CompanyId (FK) CompanyId (FK)
AccessType AddressType
Corresponding to the following C#.NET classes:
class Company
{
int Id;
List<Person> Employees;
List<Address> Addresses;
}
class Person
{
int Id;
List<Address> CompanyAddresses;
}
class Address
{
int Id;
// ...
}
It's perfectly easy to map the Person + Address collections on the Company class using NHibernate:
<class name="Company" table="Company">
<id name="Id" column="Id" />
<set name="Employees" table="Person">
<key column="CompanyId" />
<one-to-many class="Person" />
</set>
<set name="Addresses" table="Address">
<key column="CompanyId" />
<one-to-many class="Address" />
</set>
</class>
<class name="Person" table="Person">
<id name="Id" column="Id" />
</class>
<class name="Address" table="Address">
<id name="Id" column="Id" />
</class>
My problem is, how do I map the Addresses into the Person class as well? The idea is that, Companies have a list of Persons (employees) and Addresses (sites), but the Company addresses can also be looked up from the company's employees. (A bit weird and unorthodox, I know, but just play along with me on this).
Normally, I could do this by defining something like below on the Person class map:
<set name="CompanyAddresses" table="Address">
<key column="CompanyId" property-ref="CompanyId" />
</set>
... but the Person (.NET) object does NOT implement a CompanyId property for the property-ref
declaration to hold water (and we prefer for it not to).
How would I persist a collection of Addresses in the Person object via NHibernate, where Person::CompanyId = Address::CompanyId?
Thanks guys. :)
EDIT
It's actually top-of-head to just do a Person.Company.Addresses
mapping like Diego suggested below, but sadly, that won't exactly work because while a Company would have a list of Addresses, each Person linked to a Company will only have a subset of those Addresses.
I've updated the table schema above. Think of it as like if a Person has AccessType = ENGINEER, then only AddressType = ENGINEERING Addresses will be persisted in it (in addition to CompanyId = CompanyId).