views:

596

answers:

1

Hi, 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?

+3  A: 

Hi

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

Magnus Bertilsson
Brilliant! thanks.
bounav