Here is the QueryOver
version.
We are using aliasing, ie: Declaration of the null reference Employee employee = null
to be used for fully-typed access to all properties. NHibernate Expression parser will convert them into strings (column names) later based on mapping.
Also we could get references to FROM parts of the QueryOver. The query represents Employee, and the joined query represents the Department (depQuery
), which we can directly filter.
Finally we can use List() to get (SELECT) all mapped properties, or do some projection: .Select()
or .SelectList()
. With projection, we should be working with some DTO.
// aliasing, see the Projections of the SELECT clause
Employee employee = null;
Department department = null;
// the Employee query, with alias
var query = session.QueryOver<Employee>(() => employee);
// this way we can have reference to department query, if needed
var depQuery = query.JoinQueryOver<Department>(() => employee.Department, () => department);
// WHERE
// filtering the Employee
query.Where(e => e.Name == "Undefined");
// the department filtering
depQuery.Where(d => d.DeptName == "Management");
// paging, if needed
query.Skip(100);
query.Take(10);
1) select all properties
var list = query.List<Employee>();
var employeeName = list.ElementAt(0).Name;
var departmentName = list.ElementAt(0).Department.DeptName;
2) projection
// The DTO class to be projected into
public class MyDTO
{
public virtual string EmployeeName { get; set; }
public virtual string DepartmentName { get; set; }
}
// Select with projection of just two columns
MyDTO dto = null;
// SELECT
// projection, explicit property/column to be selected only
query.SelectList(l => l
// the full power of aliasing
.Select(() => employee.Name).WithAlias(() => dto.EmployeeName)
.Select(() => department.DeptName).WithAlias(() => dto.DepartmentName)
);
var list = query
.TransformUsing(Transformers.AliasToBean<MyDTO>())
.List<MyDTO>();