How to write Nhibernate Queries

23,056

Solution 1

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

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

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");

Solution 2

Simple LINQ Queries are treated as NHibernate queries, but you have to connect them to repositories.

Connect entities with Repository and IRepository to reduce its complexities.

And it will be more structured.

Use this link to understand the connection between entity and repository. http://www.asp.net/mvc/tutorials/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application

Let me know if I have taken you to right track or not.

Share:
23,056
Bhupendra Shukla
Author by

Bhupendra Shukla

Updated on May 28, 2021

Comments

  • Bhupendra Shukla
    Bhupendra Shukla almost 3 years

    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();