NHibernate:映射到对象的非规范化SQL查询

时间:2013-03-13 17:37:18

标签: sql nhibernate denormalized

我有这堂课:

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

我想使用NHibernate CreateSQLQuery

编写这个SQL查询
SELECT C.CustomerId, .... O.OrderId, O.OrderDate, O.OrderTotal.....
FROM Customers C
    LEFT OUTER JOIN Orders O ON C.CustomerID = O.CustomerID

如何进行此转换:

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

它是否包含每个Customer对象中的Orders列表?

由于

2 个答案:

答案 0 :(得分: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();

希望这会有所帮助

答案 1 :(得分: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>

NHibernate理解{c.*}{o.*},并在会话构建时将其替换为实际列。另一个优点是您可以在应用程序启动时预编译这些查询。

  var results = session.GetNamedQuery("myQuery").List<Customer>();