// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using System.Collections.Generic; using System.Linq; using NHibernate; using NHibernate.Cfg; using NHibernate.Linq; namespace NHibAggr { public class T1 { public virtual int F1 { get; set; } public virtual string F2 { get; set; } public override string ToString() { return "{" + F1 + "," + F2 + "}"; } } public class Program { public static void Traditional(ISession s) { // get one T1 o = (T1)s.Load(typeof(T1), 2); Console.WriteLine(o); // get all IList all = s.CreateQuery("SELECT o FROM T1 AS o").List(); foreach(T1 one in all) { Console.WriteLine(one); } // get some IQuery qsome = s.CreateQuery("SELECT o FROM T1 AS o WHERE f1 = :f1"); qsome.SetParameter("f1", 2, NHibernateUtil.Int32); IList some = qsome.List(); foreach(T1 one in some) { Console.WriteLine(one); } // get count IQuery qaggr = s.CreateQuery("SELECT COUNT(o) FROM T1 AS o"); IList aggr = qaggr.List(); Console.WriteLine(aggr[0]); // SQL IList fakeall = s.CreateSQLQuery("SELECT f1,'XXX' FROM T1").List(); foreach(object[] one in fakeall) { Console.WriteLine(one[0] + " " + one[1]); } } public static void Linq(ISession s) { // get one T1 o = s.Query().First(r => r.F1 == 2); Console.WriteLine(o); // get all IList all = s.Query().ToList(); foreach(T1 one in all) { Console.WriteLine(one); } // get some IList some = s.Query().Where(r => r.F1 == 2).ToList(); foreach(T1 one in some) { Console.WriteLine(one); } // get count long aggr = s.Query().Count(); Console.WriteLine(aggr); } public static void Main(string[] args) { Configuration cfg = new Configuration(); cfg.Configure("/work/nhibernateconfig.xml"); cfg.AddXmlFile("/work/nhibernatemapping.xml"); ISessionFactory sf = cfg.BuildSessionFactory(); ISession s = sf.OpenSession(); Traditional(s); Linq(s); s.Close(); } } }