Question

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?

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top