2010-04-22 171 views
0

我正在努力学习NHibernate,并且难以将SQL查询翻译为使用条件API的SQL查询。将查询翻译为NHibernate

数据模型有表:第一部分(ID,姓名,...),令(ID,PARTID,数量),运输(ID,PARTID,数量)

对于所有我想找到零件订购的总量和总量。在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

,除非你有订单货一到一个关系那么这两个查询可能会呈现不同的结果,因为如果一个订单有两个出货量,则该订单将在聚集在第一个例子计数两次。 – jishi 2010-04-22 09:11:35

+0

我会考虑重新考虑这个数据模型。或者,因为您正在使用ORM,所以从面向对象的方法开始并自动生成DB。 – UpTheCreek 2010-04-28 12:09:59

回答

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();