NHibernate QueryOver汇总集合中字段的值

时间:2012-02-22 11:58:54

标签: .net nhibernate queryover

我有一个包含子集合的父对象:

class Parent {  
    int Id {get;set;}
    ....
    IList<Child> Children {get;set;}
}

 class Child {
    int Id {get;set;}
    int Value {get;set;}
    ...
    Parent Parent {get;set;}
 }

FluentNHibernate的映射是

ParentMap:

Id(x => x.Id, "id").GeneratedBy.Assigned();
...
HasMany<Child>(x => x.Children).AsBag().KeyColumn("parentid").Inverse()
    .Fetch.Join().Cascade.AllDeleteOrphan();

ChildMap:

Id(x => x.Id).GeneratedBy.Assigned();
....
Map(x => x.Value, "value");
References<Parent>(x => x.Parent, "parentid").NotFound.Ignore();

我必须将NHibernate映射到这样的SQL查询:

select p.id, sum(c.value)
from parent p, child c
where p.id = c.parentid

是否可以使用QueryOver翻译此查询?

由于

1 个答案:

答案 0 :(得分:0)

你可以试试吗

Child childAlias = null;
var selection = session.QueryOver<Parent>()
    .JoinAlias(p => p.Childs, () => childAlias)
    .Select(Projections.Group(Projections.Id()), Projections.Sum(() => childAlias.Value))
    .List<object[]>()
    .Select(arr => new { Id = (int)arr[0], Sum = (int)arr[1] });

或者

Child parentAlias = null;
var selection = session.QueryOver(() => parentAlias)
    .Select(Projections.Id(), Projections.SubQuery(QueryOver.Of<Child>()
        .Where(c => c.Parent == parentAlias)
        .Select(Projections.Sum<Child>(c => c.Value))
    .List<object[]>()
    .Select(arr => new { Id = (int)arr[0], Sum = (int)arr[1] });

或者

IList selection = from p in session.Query<Parent>
                  select new { p.Id, Sum = p.Childs.Sum(c => c.Value) };