将查询转换为NHibernate

时间:2010-04-22 02:31:43

标签: sql nhibernate

我正在尝试学习NHibernate,并且在使用条件API将SQL查询转换为SQL查询时遇到了困难。

数据模型有表:部分(Id,Name,...),Order(Id,PartId,Qty),Shipment(Id,PartId,Qty)

对于所有部件,我想查找订购的总数量和发运的总数量。在SQL中我有:

select shipment.part_id, sum(shipment.quantity), sum(order.quantity)  
  from shipment cross join order
  on order.part_id = shipment.part_id
  group by shipment.part_id

可替换地:

select id, 
   (select sum(quantity) from shipment where part_id = part.id), 
   (select sum(quantity) from order where part_id = part.id)
  from part

但后一个查询占用的时间是原来的两倍。

关于如何在(流畅的)NHibernate中创建这些查询的任何建议?我已经映射了所有表,并且加载/保存/等实体工作正常。

1 个答案:

答案 0 :(得分:2)

嗯 - 我并没有完全了解你的模型 - 但也许这个标准对你有用。否则,请查看NHibernate文档中的criteria APIs Section Projections, aggregation and grouping

List results = session.CreateCriteria(typeof(Shipment))
    .CreateAlias("Order", order)
    .SetProjection (Projections.ProjectionList()
        .Add (Projections.GroupProperty("id"), "id)
        .Add (Projections.Sum ("Quantity"), "shipmentQuantity)
        .Add (Projections.Sum ("order.Quantity"), "orderQuantity)
    ).List();