Solved: Fluent Nhibernate SaveOrUpdate not updating DB

I had a scenario were all the select commands were working but all update commands (including delete) effecting db were not working. No errors or exceptions were being returned so it was quite hard to understand what it was. However finally, I realised that the problem was that nhibernate often commits updated once the session has been flushed.

To test if this is the issue:

After the SaveOrUpdate() command, I tried the session.flush(), and the db saved successfully.

To fix, visit the global.asax and in the Application_EndRequest add:

first add reference to:

using NHibernate;
using NHibernate.Context;

Then add the Application_EndRequest() as below:

protected void Application_EndRequest()

{

ISession mySession = ManagedWebSessionContext.Unbind(HttpContext.Current, SessionManager.SessionFactory);

if (mySession != null)
{

mySession .Flush();
mySession .Close();

}

}

If you are using transactions, I would suggest checking from active session transactions before flushing the session:

protected void Application_EndRequest()

{

ISession mySession = ManagedWebSessionContext.Unbind(HttpContext.Current, SessionManager.SessionFactory);

if (mySession != null)
{

if (mySession .Transaction != null && mySession .Transaction.IsActive)
{

mySession .Transaction.Rollback();

}
else
{

mySession .Flush();

}
mySession .Close();

}

}

Advertisements

Error: NHibernate.LazyInitializationException was unhandled by user code

Error:

When using Fluent Nhibernate I have encountered several times the following exception:

NHibernate.LazyInitializationException was unhandled by user code

In my situation, the error was showing up when I try to get details from a referenced  column. For instance, from a movies table I have several columns, one of which was CategoryID. In my details view, I wanted to display CategoryName rather than CategoryId so my code looked similar to:

string Category = movie.Category.Name.toString();

That’s when the error was coming up stating that the session was closed. However, when using:

string Category = movie.Category.Id.toString();

Cause:

The last example when I was getting the Id, the error was not fired since the CategoryId is within the same table and thus the session would be open. However, when attempting to get the Category Name, the session would be closed since that session was opened specifically for the movie table.

Solution:

To solve this I simply modified a line of code in my mapping class where I was adding the reference and added the fetch join:

before:

Id(x => x.Id);

References<Category>(x => x.CategoryId, “CategoryId”);

After:

Id(x => x.Id);

References<Category>(x => x.CategoryId, “CategoryId”).Fetch.Join();

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

Fluent Nhibernate Made Easy

fluent-nhibernate

Progressing from using NHibernate to Fluent NHibernate is a practical way of not using XML files. For people like me, who are not very comfortable using XML files, Fluent NHibernate gives the opportunity to map your domain class entities through traditional C# classes. So lets start by specifying the requirements to complete this tutorial:

Requirements for this Tutorial:

  • NuGet Package Manager (unless you already have Fluent NHibernate)
  • Visual Studio 2010
  • MS SQL 2005 or 2008

Note: If you have never used NHibernate at all, I suggest you start from my previous tutorial NHibernate made easy

This tutorial will be very similar the the previous one, however it will include all changes required to use Fluent NHibernate rather than NHibernate. Continue reading

Nhibernate simple Select, Insert, Update and Delete

nhibernate

Nhibernate is one of the many Object-Relational Mapping (ORM) tools for the .NET platform.

A very quick description of ORM:

ORM is the process of mapping objects to database relations without the requirement of writing SQL statements (such as SELECT, INSERT, UPDATE, DELETE, JOIN, etc etc) generally through the use of XML files.

Nhibernate eliminates the requirement of using ADO.NET, Linq, etc and thus is the back bone of the Data Access Layer (in nThier Architectures).

Requirements for this Tutorial:

This tutorial will be split in 12 steps:

Step 1:- Create a 2-Thier Project

Step 2:- Install Nhibernate

Step 3:- Define Business Objects (Domain Folder)

Step 4:- Define the Mapping (Mappings Folder)

Step 5:- Setting XML Schema

Step 6:- Configure Nhibernate

Step 7:- Create ISessionFactory

Step 8:- Create Table from Schema and Test Connection

Step 9:- Create Repositories

Step 10:- Define Method from Repositories

Step 11:- Testing Add, Update, Delete Method

Before we continue, I want to add that “I know this is a very long and mostly text based tutorial” but I have searched the internet sooo much for a decent working tutorial without errors and complications that this post here should cover it ALL … I also did it again while writing it to make sure no errors are found. So, hold on and read through… EVERYTHING should be there 🙂

So, lets begin …

Continue reading