I’m using NHibernate with Oracle and I’m letting NHibernate handle getting the next sequence value for my table primary keys. In the code below, I can’t seem to get NHibernate to save my object in the second call to transaction.Commit(). The database table ReportSource already has a record with the Name column set to “test2” and I have a unique constraint set on the Name column. So I expect the first transaction.Commit() to fail. But why is it the second transaction.Commit() fails after I’ve updated the ReportSource object with a name that isn’t currently in the database?
using (var session = Ioc.Container.Get<ISession>())
{
var db = new ReportSource { Name = "test2", ConnectionString = "test", Provider = "test" };
using (var transaction = session.BeginTransaction())
{
try
{
session.SaveOrUpdate(db);
transaction.Commit();
}
catch (Exception ex)
{
transaction.Rollback();
}
}
using (var transaction = session.BeginTransaction())
{
try
{
db.Name = "test4";
//fails with or without the below statement
//session.SaveOrUpdate(db);
transaction.Commit();
}
catch (Exception ex)
{
transaction.Rollback();
}
}
}
If the exception happens during a database call, you should not try to do anything else within the same session. Instead, the current session should be discarded, since it’s no longer in consistent state. That’s what NHibernate’s documentation is pointing out:
Instead of trying to have another transaction within the same session, you should create another session and try again.