2012-03-07 23 views
5

Hi tôi có một câu hỏi như thế nàyThực hiện một truy vấn tùy chỉnh trong nhibernate và bản đồ cho một đối tượng tên miền tuỳ chỉnh

SELECT Customer.Name, sum([Load].Profit) as Profit FROM Customer INNER JOIN [Load] ON Customer.Id = [Load].CustomerId GROUP BY Customer.Name 

tôi cần phải thực hiện truy vấn này trong nhibernate và bản đồ nó vào một đối tượng miền Tuỳ chỉnh mà tôi tạo ra như như thế này

public class CustomerProfit 
    { 
     public String Name; 
     public Decimal Profit; 

    } 

Có thể làm như vậy không? và làm thế nào, hoặc có thể thực hiện truy vấn tùy chỉnh này trong HQL?

+1

những gì bạn thích: a) làm việc gọn gàng cùng với bản đồ resulttransformer nhưng không changetracking b) như một thực thể với sql tùy chỉnh và làm việc nhiều hơn nhưng sự thay đổi theo dõi và các công cụ – Firo

+0

Khi yêu cầu tôi nghĩ rằng tôi muốn có một :-) – Sudantha

+0

Xem câu trả lời này http://stackoverflow.com/questions/5964147/map-sql-query-to-business-object-in-nhibernate Có thể hữu ích cho bạn;) – Gholamreza

Trả lời

14
public sealed class CustomerProfitQuery : IResultTransformer 
{ 
    public static readonly string Sql = "SELECT Customer.Name, sum([Load].Profit) as Profit FROM Customer INNER JOIN [Load] ON Customer.Id = [Load].CustomerId GROUP BY Customer.Name"; 
    public static readonly CustomerProfitQuery Transformer = new CustomerProfitQuery(); 

    // make it singleton 
    private CustomerProfitQuery() 
    { } 

    public IList TransformList(IList collection) 
    { 
     return collection; 
    } 

    public object TransformTuple(object[] tuple, string[] aliases) 
    { 
     return new CustomerProfit 
     { 
      Name = (string)tuple[0], 
      Profit = (decimal)tuple[1], 
     }; 
    } 
} 


// usage 
var customerprofits = session.CreateSQLQuery(CustomerProfitQuery.Sql) 
    .SetResultTransformer(CustomerProfitQuery.Transformer) 
    .List<CustomerProfit>() 
+1

Gr8 ... hoàn toàn phù hợp với tôi .. giải pháp gr8 .. –

Các vấn đề liên quan