views:

465

answers:

1

Hi,

I have a scenario where I need to do the following in a transaction: 1. Save a model with a unique key 2. Delete that model 3. Save a new model with the same unique key the first one had.

I'd expect this to work just fine, but I get a unique key violation.

NH Profiler also shows that the delete statement is not issued before the second insert.

My mapping looks as follows:

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="NHTest">
  <class name="UniqueKeyModel" table="UniqueKeyModels">
    <id name="Id">
      <generator class="hilo"/>
    </id>

    <property name="TheVal" unique-key="valuniqueness" type="System.String"></property>
  </class>
</hibernate-mapping>

My model:

public class UniqueKeyModel
{
   public virtual long Id { get; private set; }
   public virtual string TheVal { get; set; }
}

My Testcase:

ISession sess = ...;

UniqueKeyModel mFirst = new UniqueKeyModel { TheVal = "value" };
sess.Save(mFirst);
sess.Delete(mFirst);

UniqueKeyModel mSecond = new UniqueKeyModel { TheVal = "value" };
sess.Save(mSecond);
A: 

I think you should flush the session after the delete. Changes are written to the database when you flush a session. (If you are using transactions you have to start a new one after flushing the session)

bernhardrusch
Thanks. A Flush() after Delete() apparently solves this issue.I neglected to state that I was using transactions. e.g. using (ISess ...) using (ITansaction t = sess.BeginTransaction() ...).The session.flush does not appear close the transaction, as I can rollback the entire transaction after a .Flush.
Thank you for your tip (in our application we are closing the transaction with the flush) - I've corrected my answer...
bernhardrusch