2

我的实体如下:

(1) Course (with details) (2) Student (with details) (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 世界的新手,因此我的问题可能是非常初步的。

谢谢

4

2 回答 2

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>();
于 2013-01-23T05:29:17.413 回答
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>();
于 2013-01-24T23:36:42.157 回答