How to a write a Criteria query with multiple joins involved

走远了吗. 提交于 2019-12-08 03:08:10

问题


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 objects : User(ID, Name, Role, Customer), Role(ID, Name) and Customer(ID, Name).

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?


回答1:


You can use alias

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>();

Hope it helps



来源:https://stackoverflow.com/questions/372047/how-to-a-write-a-criteria-query-with-multiple-joins-involved

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!