LINQ for Nhibernate

References Required:

  • using Domain;   //this is the folder where your entities are found
  • using NHibernate;
  • using NHibernate.Criterion;

Other Requirements:

  • Nhibernate / Fluent Nhibernate
  • Linq for Nhibernate
  • Nhibernate Session Helper (can find ready ones on the internet)

1. Return a row by integer Id

public Movies GetById(intId)

using(ISession session = NHibernateHelper.OpenSession())

return session.Get<Icon>(Id);


2. Return a simple IList<> / Return all rows in a table:
public IList<Movies> GetAll()

using(ISession session = NHibernateHelper.OpenSession())

return session.CreateCriteria(typeof(Movies)).List<Movies>();


3. Return an IList<> with a WHERE clause:

public IList<Movies> GetMoviesByCategory(int CatId)

using(ISession session = NHibernateHelper.OpenSession())

return session.CreateCriteria(typeof(Movies)).Add(Restrictions.Eq(“CategoryId”, CatId)).List<Movies>();


4. Return an IList<> with a 3-way JOIN and WHERE clause

public IList<MovieImages> GetMovieImagesByMovieCategory(int CatId)

IList<Movie> movies = GetAllMovies(); //Change with your query
IList<MovieCategory> categories = GetAllCategories(); //Change with your query
IList<MovieImages> images = GetAllImages(); //Change with your query

using(ISession session = NHibernateHelper.OpenSession())

return (from mi in images
join m in movies on mi.Movie.Id equals m.Id
join c in categories on m.CategoryId.Id equals c.Id
where c.Id == category.Id
select mi).ToList<MovieImages>();


5.Convert List to IList<>

IList<MovieImages> list = myNormalList.ToList<MovieImages>(); //myNormalList would be a common List()

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s