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

Advertisements

Linq to SQL using Stored Procedures in nThier Design

After doing a lot of research, I realised that when using Linq to Sql to communicate with the database, it is quite impossible or too complicated to use datatables or datarows. In this example I will demonstrate an easy and quick way to retrieve a whole table from a database using stored procedures assuming we are using a three thier design.

Continue reading

LinQ to SQL simple Insert Update and Delete

Since I was given a task to implement new technologies, I came about selecting LinQ. It was quite hard to find a simple place or tutorial where I could find how to do simple queries without complexities. Therefore I decided to post a blog to describe as simple as can be the process of inserting updating and deleting from LinQ to SQL.

Continue reading