NHibernate - map the same object to different tables in the same database

Suppose we have an Employee object that consists of several other objects, such as one-to-many addresses and contacts, and several fields (name, age, etc.). We displayed this object and can use it just fine, saving each part in the tables “Employee”, “Employees” and “Employees”.

However, we use almost all of this information about employees for a large calculation and have a separate "EmployeeInput" object consisting of the same lists of Address and Contact objects (that is, both the Employee object and EmployeeInputs have a list of person addresses and contacts) . We need to keep this information when we earn the calculation for future audit purposes. We want to save this EmployeeInput object in the "EmployeeInput" table in the database.

The problem we are facing is how to save address and contact lists? We would like to insert them into something like "EmployeeInputAddresses" and "EmployeeInputContacts", but the addresses and contacts are already mapped to "EmployeeAddresses" and "EmployeeContacts" respectively.

The easiest way to accomplish this is without creating a new entity "EmployeeInputAddress" and "EmployeeInputContact" and separate mapping files for each (since the fields will be literally duplicated one by one). In other words, how can we map a single entity, an address, to two different tables depending on the parent object to which it belongs (the EmployeeAddresses table if it saves the Employee object and the EmployeeInputAddresses table if it saves the EmployeeInput object).

+4
source share
1 answer

The easiest way is to have addresses and contacts displayed as composite items. That way, you could map your collection differently for Employee and for EmployeeInput , since the mapping belongs to the container.

For instance:

 public class Employee { public List<Address> Addresses{get; set;} } public class EmployeeInput { public List<Address> Addresses{get; set;} } public class Address { public string Street{get;set;} public string City{get; set;} } 

Will have the following mapping:

 <class name="Employee" table="Employees"> <id name="id"> <generator class="native"/? </id> <list name="Addresses" table="EmployesAddresses"> <key column="Id" /> <index column="Item_Index" /> <composite-element class="Address"> <property name="Street" /> <property name="City" /> </composite-element> </list> </class> <class name="EmployeeInput" table="EmployeesInput"> <id name="id"> <generator class="native"/? </id> <list name="Addresses" table="EmployeesInputAddresses"> <key column="Id" /> <index column="Item_Index" /> <composite-element class="Address"> <property name="Street" /> <property name="City" /> </composite-element> </list> </class> 
+5
source

All Articles