Most likely, the Department class is not entirely useless. What does the following code mean?
plan.ExecutorDepartment = "Hyoomun Reesorsis";
plan.ExecutorDepartment = "Human Resources";
You can't tell if we're just fixing the spelling or if we're assigning it to a different department.
Is it ever possible for the name of a department to change? If so, does that change need to be reflected in all Plans that belong to that department? If that's the case, then from a Domain Driven Design perspective, a Department is an entity, not a value object. If it's an entity, then you should continue to map those relationships with many-to-one
and many-to-many
. This makes your code more descriptive. To fix the spelling, you say...
plan.ExecutorDepartment.Name = "Human Resources";
... or to assign the plan to a new department, you say:
plan.ExecutorDepartment = theOtherHrDepartmentThatActuallyCaresAboutSpelling;
This version of the code is much clearer about what it is trying to do.
NHibernate is a tool that allows you to work with your relational database in an object-oriented, domain-driven fashion. It works best when you try to follow DDD rules. What you are asking to do doesn't make sense from a DDD perspective, because Department does have an identity, so NHibernate doesn't support pretending that it doesn't have identity. There is no mapping for what you want to do. If you need to model it this way, you have a few options.
A. Add properties to dig in and get the strings for you.
public virtual string ExecutorDepartmentName
{
get { return ExecutorDepartment != null ? ExecutorDepartment.Name : null; }
}
public virtual IEnumerable<string> AdditionalExecutorDepartmentNames
{
get { return AdditionalExecutorDepartments.Select(x => x.Name); }
}
B. Change the database schema, removing the Department
table, and replacing any Department_id
columns with DepartmentName
. Do this if department really is supposed to be a value object, not an entity. After changing the schema, your mappings would need to change from many-to-one
and bag
many-to-many
, to property
and bag
element
.
C. If what you want is similar to option "A", but you also want to be able to change departments without messing with the Department_id
- you can get something like that if you change Department
's primary key to be the string name (provided that it is unique and not null). This will allow you to use session.Load
to get a Department instance from the string name without hitting the database.
So, all of this probably isn't the silver bullet "here's this amazing mapping you didn't know about" that you were hoping for, but these are all of the realistic options I could think of, and you should be able to find something that meets your needs within this list.