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

}

}

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