How to write Nhibernate Queries

asp.net-mvc-4, c#, linq, nhibernate, sql

Solution

The documentation for NHibernate querying is pretty good and complete. The basic knowledge you can find here:

- Chapter 15. Criteria Queries

The `QueryOver` API, which is the fully typed version of `Criteria` is documented here:

- Chapter 16. QueryOver Queries

Start to observe the API documentation. Soon you will see that it is pretty logic (`.Where()` to build WHERE, `.Select()` to adjust SELECT....). Later, if any issues, SO is full of HOW TO

An example from 16.1 adjusted to Employee:

var list = session
        .QueryOver<Employee>()
        .WhereRestrictionOn(c => c.Age).IsBetween(18).And(60)
        .Select(c => c.Name)
        .OrderBy(c => c.Name).Asc
        .List<string>();

A JOIN to Department (adjusted example from 16.4)

var query = session
        .QueryOver<Employee>()
        .JoinQueryOver(e => e.Department)
            .Where(k => k.DeptName == "Director");

Problem

I have two class in which are mapped in the database. The tables have primary and foreign key relation with each other with the field "DeptId". Employee.cs ``` public class Employee: Entity { public virtual Int32 Id { get; set; } public virtual string Name { get; set; } public virtual string Gender { get; set; } public virtual Int32 Age { get; set; } public virtual string Designation { get; set; } public virtual bool Enabled { get; set; } public virtual int CreatedById { get; set; } public virtual DateTime CreatedDate { get; set; } public virtual int? LastModifiedById { get; set; } public virtual DateTime? LastModifiedDate { get; set; } public virtual bool IsDeleted { get; set; } public virtual Department Department { get; set; } } ``` Department.cs ``` public class Department { public virtual int DeptId { get; set; } public virtual string DeptName { get; set; } public virtual bool Enabled { get; set; } } ``` As i am new to NHibernate, i am unable to write the more complex Linq queries using QueryOver. I have written the following query but how can i write the more advance queries. please provide me sample queries and references for this. ``` var query = Session.QueryOver<Employee>().List(); ```

Original source