本文介绍了如何编写包含多个联接的条件查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用Criteria API对以下HQL查询进行编码:
I'm trying to code the following HQL query using the Criteria API:
var userList = _session
.CreateQuery("select u from User u where u.Role.ID=3 and u.Customer.ID=:cID")
.SetInt32("cID", 1)
.List<User>();
(3个NHibernate对象:用户(ID,名称,角色,客户),角色(ID,名称)和客户(ID,名称).
(3 NHibernate objects : User(ID, Name, Role, Customer), Role(ID, Name) and Customer(ID, Name).
我尝试了以下操作,但由于NHibernate试图找到与某个角色相关联的客户而无法使用:
I tried the following but it doesn't work because NHibernate tries to find a Customer associated with a Role:
var userList = _session
.CreateCriteria(typeof(User))
.CreateCriteria("Role")
.Add(Restrictions.Eq("ID", 3) )
.CreateCriteria("Customer")
.Add(Restrictions.Eq("ID", 1) )
.List<User>();
还有其他可行的方法吗?
Any other way (that works!) of doing it?
推荐答案
您可以使用别名
var userList = _session
.CreateCriteria(typeof(User), "u")
.CreateAlias("u.Role", "r")
.Add(Restrictions.Eq("r.ID", 3) )
.CreateAlias("u.Customer", "c")
.Add(Restrictions.Eq("c.ID", 1) )
.List<User>();
希望有帮助
这篇关于如何编写包含多个联接的条件查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!