Reputation: 29301
I'm clearly doing something wrong here. I don't understand why NHibernate is trying to commit anything in this scenario.
I've supplied a 'Description' field which is >200 characters in length. I have a validator which is called:
Order.ValidateAndThrow(Order);
RuleFor(order => order.Description).Length(0, 200).WithName("Description");
Because my description has a length greater than 200 characters -- ValidateAndThrow throws an exception.
Here's the catch block that handles the exception:
catch (Exception exception)
{
Logger.Error(exception);
NHibernateSessionManager.Instance.RollbackTransaction();
throw;
}
public void RollbackTransaction()
{
ITransaction transaction = ContextTransaction;
try
{
if (HasOpenTransaction())
{
transaction.Rollback();
}
ContextTransaction = null;
}
finally
{
CloseSession();
}
}
/// <summary>
/// Flushes anything left in the session and closes the connection.
/// </summary>
public void CloseSession()
{
ISession session = ContextSession;
if (session != null && session.IsOpen)
{
session.Flush();
session.Close();
}
ContextSession = null;
}
So, what I see happening is that the transaction.Rollback() statement executs successfully and then CloseSession() is called.
Inside of CloseSession(), session.Flush() is executed. This causes my Order entity to, apparently, try and be saved to the database. I thought I had just rolled back my change, though?
Nevertheless, calling SessionClose() generates a GenericADOException. The inner exception message reads "{"String or binary data would be truncated.\r\nThe statement has been terminated."}"
How should I properly exit my transaction in this scenario?
Upvotes: 0
Views: 1569
Reputation: 6103
According to the doc here
If you happen to be using the ITransaction API, you don't need to worry about this step [flushing the session]. It will be performed implicitly when the transaction is committed.
So if you are using NHibernate's ITransaction.Commit()
there is no need to flush. And if the transaction was rolled back, you definitely don't want to flush. Just make sure you always close the session.
Upvotes: 1