Jim Carragher
Jim Carragher

Reputation: 313

NHibernate: Saving stops when hitting a unique constraint

I'd like to save a list of stores into the database using NHibernate. However, there is a unique constraint on each store, causing the save to stop when a store triggers the constraint.

try
{
    _storeRepository.Save(stores);
}
catch (Exception e)
{
}
finally
{
    session.Commit();
}

In accordance with to the code above, all stores before the unique constraint is hit are saved, but not the ones after. How can I fix this without having to loop the whole list and check for duplicates?

Upvotes: 0

Views: 667

Answers (2)

Stefan Steinegger
Stefan Steinegger

Reputation: 64628

The rules are:

  • Never catch sql (or NH) Exceptions in the transaction.
  • in case of an error, always rollback to whole stuff
  • in case of an error, always destroy the session.

The NH session cache gets out of synch and you can't use it anymore. So "finally commit" is a very bad thing.

You need to make sure that you don't violate any database constraint in your business logic.

Upvotes: 1

rebelliard
rebelliard

Reputation: 9611

You could always use the SaveOrUpdate so NHibernate updates the entity if one with the given entity is found in the database.

Upvotes: 0

Related Questions