带有连接和分组的NHibernate查询

时间:2011-11-15 08:34:40

标签: c# nhibernate criteria-api

我有4个相关的课程,需要进行查询。

课程是:

 public class Project{

     IList<Process> Processes{get;set;}

 }


 public class Process{

     IList<Association> Associations{get;set;}

 }


 public class Association{

     public IList<MonthCapacity> MonthCapacities{get;set;}
     public FieldOfActivity FieldOfActivity{get;set;}

 }

 public class MonthCapacity{

     public int Hours{get;set;}
     public DateTime MonthDate{get;set;}

 }

 public class FieldOfActivity{

 }

查询应该产生DTO:

 public class ChartDto{

      public Project Project{get;set;}
      public FieldOfActivity FieldOfActivity{get;set;}
      public int Hours{get;set;}

 }

我尝试使用QueryOver,但没有让它工作。有人可以帮助我吗?

先谢谢Tobi

1 个答案:

答案 0 :(得分:2)

你可以测试一下这个:

Process processAlias = null;
Association assocAlias = null;
FieldOfActivity actAlias = null;

var subquery = QueryOver.Of<MonthCapacity>()
    .Where(m => m.Association == assocAlias)
    .Select(Projections.Sum<MonthCapacity>(m => m.Hours));

var results = session.QueryOver<Project>()
    .JoinQueryOver(p => p.Processes, () => processAlias)
    .JoinQueryOver(p => p.Associations, () => assocAlias)
    .JoinAlias(p => p.FieldOfActivity, () => actAlias)
    .Select(p => new ChartDto { Project = p, FieldOfActivity = actAlias, Hours = Projections.Subquery(subquery) })
    .List();

编辑:

var results = session.QueryOver<Project>()
    .JoinQueryOver(p => p.Processes, () => processAlias)
    .JoinQueryOver(p => p.Associations, () => assocAlias)
    .JoinAlias(p => p.FieldOfActivity, () => actAlias)
    .SelectList(list => list
        .Select(p => new ChartDto { Project = p, FieldOfActivity = actAlias, Hours = 0 })
        .Select(Projections.Subquery(subquery))
    )
    .List<object[]>()
    .Select(objects =>
    {
        var chart = (ChartDto)objects[0];
        chart.Hours = (int)objects[1];
        return chart;
    });