I'm in a early phase of learning NHibernate, and currently I'm trying to select every person within a company or function. The code is listed below. I have some problems with conditions on the Person's associated properties. The person has one-to-many relation to Department, and I want to check the DepartmentName property of the related department. This is the same for Function, but I guess I'll manage that when I've understood the problems with Department. What am I doing wrong? :)
using (var session = NHibernateHelper.OpenSession())
{
var criteria = session.CreateCriteria(typeof(Person));
if (!string.IsNullOrEmpty(employeeNumber))
{
int emplNum;
int.TryParse(employeeNumber, out emplNum);
criteria.Add(Restrictions.Eq("EmployeeNumber", emplNum));
}
if (!string.IsNullOrEmpty(name))
{
foreach (var token in name.Split(' '))
{
var expr = string.Format("%{0}%", name);
criteria.Add(Restrictions.Or(
Restrictions.Like("FirstName", expr),
Restrictions.Like("LastName", expr)
));
}
}
if (!string.IsNullOrEmpty(department))
{
var expr = string.Format("%{0}%", department);
criteria.SetFetchMode("Department", NHibernate.FetchMode.Eager);
criteria.Add(Restrictions.Like("Department.DepartmentName", expr));
}
if (!string.IsNullOrEmpty(function))
{
var expr = string.Format("%{0}%", function);
criteria.SetFetchMode("Function", NHibernate.FetchMode.Eager);
criteria.Add(Restrictions.Like("Function.FunctionName", expr));
}
return criteria.List<Person>();
Update
I managed to do it by myself. I changed the department part to this:
if (!string.IsNullOrEmpty(department))
{
var expr = string.Format("%{0}%", department);
criteria.CreateAlias("Department", "dep")
.SetFetchMode("Department", FetchMode.Eager)
.Add(Restrictions.Like("dep.DepartmentName", expr));
}
Still, this might not be the preferred way, so leave a comment if I'm doing something horribly wrong :-)