How to remove entity from session when error on Save and the auto-increment Id has not been generated

StackOverflow https://stackoverflow.com/questions/17213291

Question

NHibernate version: 3.3.2.

I have a NHibernate transaction with several operations. As one of the intermediate steps in the transaction, I try to insert a new entity instance with an auto-increment PK via Session.Save.

In some cases there is an error in the insertion caused by a violated Foreign Key value. I catch the exception in order to make some logging and ignore it, assuming the insert has not been done and going on with the following steps. This is a functional requirement and can not be changed. Validating the values before inserting is not an acceptable solution either, according to performance requirements.

My problem: the non-persisted entity has been added to NH session cache but with an empty Id. So I get this exception later when doing some other NH operations:

NHibernate.AssertionFailure: null id in MyApp.MyPackage.MyClass entry (don't flush the Session after an exception occurs)

My question: how can I pull this annoying "zombie" entity off of the session, so I can successfully commit the transaction at the end of all steps?

I can't Evict it, because the Id is empty.

I tried it and got following exception:

System.InvalidOperationException: cannot generate an EntityKey when id is null

I can't either Clear() the current session as I am in the middle of a transaction and have some previous and following steps to be preserved.

The original exception I got was somewhat confusing, and was thrown at a different point from where the real problem was originated. This link gave me some information to figure out what was happening: NHibernate - null id in entry (don't flush the Session after an exception occurs)

Was it helpful?

Solution

According to NHibernate Manual, 9.8. Exception handling:

If the ISession throws an exception you should immediately rollback the transaction, call ISession.Close() and discard the ISession instance. Certain methods of ISession will not leave the session in a consistent state.

I guess you have to restart the whole transaction in your case.

OTHER TIPS

As much as it sucks, I've been able to get around this by wrapping my zombie.discard() in a 'try/catch', and when I do so, it suppresses the nastier "null id in your.object entry (don't flush the Session after an exception occurs)"

I feel dirty.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top