我是nHibernate的新手。我有以下SQL内连接查询,
SELECT e.name,
d.deptname
FROM demo_employee AS e
INNER JOIN demo_department AS d
ON e.departmentid = d.deptid
使用以下sql查询的Query Over的linq表达式是什么。
我已经编写了以下查询,但它在以下地方“c.Department.DeptId”给我错误。
var Query =
Session.QueryOver<Employee>()
.JoinQueryOver<Department>(c => c.Department.DeptId)
.Where(k => k.Name == k.DeptId);
答案 0 :(得分:2)
这是QueryOver
版本。
我们正在使用别名,即: null 引用Employee employee = null
的声明,用于对所有属性进行完全类型的访问。 NHibernate Expression解析器稍后将根据映射将它们转换为字符串(列名)。
我们也可以获得对QueryOver的FROM部分的引用。 查询代表Employee,加入的查询代表部门(depQuery
),我们可以直接过滤。
最后,我们可以使用List()来获取(SELECT)所有映射的属性,或者进行一些投影:.Select()
或.SelectList()
。通过投影,我们应该与一些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)选择所有属性
var list = query.List<Employee>();
var employeeName = list.ElementAt(0).Name;
var departmentName = list.ElementAt(0).Department.DeptName;
2)投影
// 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>();