开发者

NHibernate HQL queries

How to write HQL queries using NHibernate. What namespaces will I have to included so that everything works fine. Actually I have 2 tables Ticket and Trip and I wanta count of all the records in Trip that do not have a corresponding entry in Ticket. There is a tid field in ticket that refrences Trip id. Can anybody please explain me f开发者_JAVA百科rom start how will I write a NHibernate HQL query for this?


You don't need any special namespaces to use HQL. Just create a simple NHibernate project and you can start writing HQL right away.

Here is an example from the new NHibernate 3.0 Cookbook and you should also check the Nhibernate in Action book which has a more elaborate examples on HQL.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate.Cfg;
using NHibernate;

namespace ExecutableHQL
{
  class Program
  {
    static void Main(string[] args)
    {
      log4net.Config.XmlConfigurator.Configure();
      var nhConfig = new Configuration().Configure();
      var sessionFactory = nhConfig.BuildSessionFactory();

      using (var session = sessionFactory.OpenSession())
      {
        using (var tx = session.BeginTransaction())
        {
          int count = (int) session.CreateQuery("select count(*) from Trip").UniqueResult();

          tx.Commit();
        }
      }
    }
  }
}


    [HttpGet]
    public int GetCount()
    {
        var myQuery = session.CreateQuery(@" 
        select COUNT(*) from Table as t where 
        t.Id = :Id");
        myQuery.SetParameter("Id", this.Id);
        int count = Convert.ToInt32(myQuery.UniqueResult());
        return count;
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜