0

I have a sql query as below:

SELECT * 
FROM   USER R 
       INNER JOIN userdepartment C 
               ON R.id = C.userid 
       INNER JOIN userdepartment K 
               ON C.userid = K.userid 
WHERE  C.departmentid = 155 
       AND K.departmentid = 157 

User and Department have Many-To-Many relation and to maintain the relation, I have UserDepartment table. Now I want to fetch only those Users who have both Departments with Id 155 and 177. The above query does what I want.

Now I want to convert the above query into an Nhibernate query. I am using Criteria to generate queries. I have tried the following:

    var criteria =    Session.CreateCriteria<User>();
    var subcriteria = criteria
                      .CreateCriteria("UserDepartments","a", JoinType.InnerJoin);
    subcriteria = subcriteria
                       .CreateCriteria("UserDepartments", "b", JoinType.InnerJoin);
    var conjunction = Restrictions.Conjunction();
    conjunction.Add(Restrictions.Eq("DepartmentId", 155));
    conjunction.Add(Restrictions.Eq("DepartmentId", 177));
    subCriteria.Add(conjunction);

But this does not work. Please help me with the same. Thanks in advance for your help.

frictionlesspulley
  • 11,070
  • 14
  • 66
  • 115

1 Answers1

0

Your query not working because the userdepartment to userdepartment relation not exists in the userdepartment in the configuration. you have to create a children of userdepartment in the userdepartment. Then you can access that children. This is because nhibernate use relations defined in the configuration to traverse.