0
votes

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);
1

1 Answers

0
votes

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)