2013-03-13 98 views
1

我有這個類:的NHibernate:規格化SQL查詢映射到一個對象

public Customer 
{ 
    public int CustomerId {get;set;} 
    .... 
    public List<Order> OrderList {get;set;} 
} 

我想寫使用NHibernate CreateSQLQuery

SELECT C.CustomerId, .... O.OrderId, O.OrderDate, O.OrderTotal..... 
FROM Customers C 
    LEFT OUTER JOIN Orders O ON C.CustomerID = O.CustomerID 

如何使這種轉變工作這個SQL查詢:

.SetResultTransformer(Transformers.AliasToBean<Customer>()) 

並讓它包含每個Customer對象內的Orders列表?

感謝

回答

0

假設你的結果映射到你的實體的屬性名稱的所有列名,您可以嘗試:

var myQuery = @"SELECT C.CustomerId, .... O.OrderId, O.OrderDate, O.OrderTotal..... 
        FROM Customers C 
        LEFT OUTER JOIN Orders O ON C.CustomerID = O.CustomerID"; 

myNHSession.CreateSQLQuery(myQuery) 
      .AddEntity("C",typeof(Customer)) 
      .AddJoin("O","C.OrderList") 
      .List(); 

希望這將有助於命名查詢

0

使用,如果你能。

<sql-query name="myQuery"> 
    <return alias="c" class="Customer" /> 
    <return-join alias="o" property="c.Orders" /> 
    <![CDATA[ 
    SELECT {c.*}, {o.*} FROM Customers c LEFT OUTER JOIN Orders o ON c.CustomerId = o.CustomerId 
    ]]> 
</sql-query> 

{c.*}{o.*}由NHibernate的理解和在會話建立時間的實際列替換。另一個優點是可以在應用程序啓動時預編譯這些查詢。

var results = session.GetNamedQuery("myQuery").List<Customer>(); 
相關問題