NHibernate View Mapping
Consider an application consisting of Employees
and Administrators
.
An employee
consists of an EmployeeId
, Name
and EmailAddress
.
The employees are stored in a legacy system and are readonly so I have an immutable Employee
class mapped to a view (vw_Employee
) as follows:
[vw_Employee] -> EmployeeID(key), Name, EmailAddress
Now for this application, some of the employee's will be marked as administrators (Image a screen with a drop down list of employees, you select one, click add and that employee is now an administrator).
An administrator is an employee (has exactly the same fields) so the database table only needs to look like the following:
[Administrators] -> EmployeeID(key)
In the same application, I will need to display a list of all the administrators names and email address
Without NHibernate I could get a list of administrators by joining the [Administrators]
table with the [vw_Employee]
view using the EmployeeID
primary key.
The issue I'm having is what should the Administrator
class look like and how would I map this using NHibernate.
Any help would be mu开发者_如何学运维ch appreciated
From an OO point of view, and Administrator is not an employee, but it has a 1-1 relationship with employee.
So, your classes would be:
public class Employee
{
...
}
public class Administrator
{
public virtual TypeOfEmployeeId Id { get; protected set; }
public virtual Employee Employee { get; set; }
}
Since Employee is immutable, it doesn't matter that it's a view.
Mapping is simple too:
<class name="Administrator">
<id name="Id">
<generator class="foreign">
<param name="property">Employee</param>
</generator>
</id>
<one-to-one name="Employee"/>
</class>
And usage couldn't be simpler:
Employee employee = GetTheEmployee();
var administrator = new Administrator { Employee = employee };
session.Save(administrator);
精彩评论