Write subquery in Criteria of nHibernate

心不动则不痛 提交于 2019-12-04 05:14:41

Well - the code should be something like this:

DetachedCriteria dc = DetachedCriteria.For<Employee>()
.Add (Subqueries.PropertyIn("EmployeeId",
     DetachedCriteria.For<Employee>()
         .SetProjection(Projections.Property("EmployeeId"))
         .Add(Restrictions.Lt("No_Of_years_working", 10))
         .Add(Restrictions.Eq("Post", "Manager"))
);

Hope this helps.

I was trying to perform something similar to Bipul's task, when I found this question, so I mainly got bernhardrusch's answer idea, but I've realized that without adding the Projections.projectionList the subquery do not work. So I've decided to drop a few lines of code with the final version:

Session session; //You get the session according with your app logic

//Let's define first the subquery
DetachedCriteria sub = DetachedCriteria.forClass(Employee.class);
sub.add( Restrictions.lt("No_Of_years_working", 10) );
sub.add( Restrictions.eq("Post", "Manager") );
sub.setProjection( 
Projections.projectionList().add(                   Projections.property("EmployeeId") 
) 
);

//Now the main query
Criteria criteria = session.createCriteria(Employee.class);
criteria.add( Property.forName("EmployeeId").in(sub) ); 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!