Denis Morgan

Denis Morgan

  • NA
  • 72
  • 22.6k

Nhibernate generic method to Query different Model

Sep 7 2020 11:57 PM
I have created a generic function for nHibernate to convert List to Bean which works fine however I need a way to do conversion in a generic way without calling AddScalar(as commented in my code) to my query that is assume I have over 50 model pojo and want to use same generic method to pull list of records how can I achieve this. This is my generic Method that I want to use to any model and pass associated query.
  1. public static IList<T> getRawQuery<T>(string query)//  
  2. {  
  3.     IList<T> ls = new List<T>();  
  4.     ISession session = MyHibernateUtil.openSession();  
  5.     try  
  6.     {  
  7.         ls = session.CreateSQLQuery(@query)  
  8.             .AddScalar("total", NHibernate.NHibernateUtil.Int32)//dont want to do this  
  9.             .AddScalar("product_name", NHibernate.NHibernateUtil.String)//this will force me to have several methods doing same work  
  10.             .AddScalar("barcode", NHibernate.NHibernateUtil.String)  
  11.             .SetResultTransformer(Transformers.AliasToBean(typeof(T)))  
  12.             .List<T>();  
  13.   
  14.     }  
  15.     catch (Exception ex)  
  16.     {  
  17.         Console.WriteLine(ex);  
  18.     }  
  19.     finally  
  20.     {  
  21.         MyHibernateUtil.CloseSession(session);  
  22.     }  
  23.     return ls;  
  24. }  
and here is my one of my model
  1. public class SalesModel  
  2. {  
  3.     public virtual String barcode { getset; }  
  4.     public virtual String product_name { getset; }  
  5.     public virtual int total { getset; }  
  6. }