简体   繁体   中英

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 from 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;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM