I'm new to 开发者_StackOverflow中文版Criteria API in NHibernate. Can someone generate this piece of SQL using Criteria API in NHibernate?
select count(*)
from result where Student_id
in(
SELECT s.Student_id
from Department as d
JOIN Student s ON d.Dept_id=s.Dept_id
where d.Dept_id=2
)
and how to proceed through the Criteria API in NHibernate. P.S I don't want to use HQL so without HQL is it possible to generate this kind of sql in nhibernate?
You can use linq-2-nhibernate as well.
Given the following class structure:
public class Result{
public virtual Student Student {get; set;}
}
public class Student{
public virtual Department Department {get; set;}
public virtual int Id { get; set;}
}
public virtual Department {
public virtual int Id {get; set;}
public virtual IList<Student> Students {get; set;}
}
Here is your query using the Criteria API:
var studentidquery = DetachedCriteria.For<Student>()
.Add(Restrictions.Eq("Department.Id"),2)
.SetProjection(Projections.Property("Id"));
var count = session.CreateCriteria<Result>()
.Add(Subqueries.PropertyIn("StudentId", studentidquery))
.UniqueResult<int>();
Using the QueryOver API it would look like this:
var studentidquery = QueryOver.Of<Student>()
.Where(x=>x.Department.Id==2)
.Select(x=>x.Id);
var count = session.QueryOver<Result>()
.WithSubquery.WhereProperty(x => x.Id).In(studentidquery)
.Select(Projections.Count<Result>(r=>r.Id))
.UniqueResult<int>();
Also I don't think you need the join to Department in your SQL query as you already have DepartmentId as a foreign key in the Student table. No sense in joining to extra tables for no good reason.
精彩评论