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

}

}

Leave a Reply

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

WordPress.com Logo

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

Google photo

You are commenting using your Google 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