2010-04-22 183 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();