我的实体如下:
(1)课程(详情) (2)学生(详情) (3)StudentEnrolment(具有一对多的学生到课程的映射)
现在我正在尝试创建一个投影类(名为CourseSummary),其中包含课程的几个字段以及该课程中的学生总数(称为TotalEnrolments)。在下面的代码中,我也包括课程的校园(虽然与我的问题无关)。
我到达这里:
var courseSummaries = session.CreateCriteria<Course>()
.CreateAlias("Campus", "cmp")
.SetProjection(Projections.ProjectionList()
.Add(Projections.Property("CourseId"), "CourseId")
.Add(Projections.Property("StartDate"), "StartDate")
.Add(Projections.Property("EndDate"), "EndDate")
.Add(Projections.Property("cmp.CampusId"), "CampusId")
//What here for "TotalEnrolments"?
).SetResultTransformer(Transformers.AliasToBean<Course>())
.List<Course>();
但我该如何加入StudentEnrolment课程并从中获取相关记录的总数?
我是NHibernate世界的新手,因此我的问题可能非常初步。
由于
答案 0 :(得分:3)
var courseSummaries = session.CreateCriteria<Course>("c")
.CreateAlias("Campus", "cmp")
.SetProjection(Projections.ProjectionList()
.Add(Projections.Property("CourseId"), "CourseId")
.Add(Projections.Property("StartDate"), "StartDate")
.Add(Projections.Property("EndDate"), "EndDate")
.Add(Projections.Property("cmp.CampusId"), "CampusId")
.Add(Projections.Subquery(DetachedCriteria.For<Student>()
.Add(Restriction.Eq("Course.Id", "c.Id"))
.SetProjections(Projections.RowCount()), "TotalStudents")
)
.SetResultTransformer(Transformers.AliasToBean<CourseSummary>())
.List<CourseSummary>();
答案 1 :(得分:1)
在完成Firo的回答并做了一些自我调整之后,我解决了它,如下所示:
var courseSummaries = session.CreateCriteria<Course>("c")
.CreateAlias("Campus", "cmp")
.SetProjection(Projections.ProjectionList()
.Add(Projections.Property("CourseId"), "CourseId")
.Add(Projections.Property("StartDate"), "StartDate")
.Add(Projections.Property("EndDate"), "EndDate")
.Add(Projections.Property("cmp.CampusId"), "CampusId")
.Add(Projections.Subquery(DetachedCriteria.For<StudentEnrolment>("s")
.Add(Restriction.EqProperty("s.Course.CourseId", "c.CourseId"))
.SetProjections(Projections.RowCount()), "TotalStudents")
)
.SetResultTransformer(Transformers.AliasToBean<CourseSummary>())
.List<CourseSummary>();