NHibernate Invalid Index For This SqlParameterCollection

Monday, November 10 2008 -

I ran into a problem last week where I kept getting this exception: Invalid index 6 for this SqlParameterCollection with Count=6.

I spent a lot of time trying to figure out what object was causing the issue. Individually, each object would persist correctly, but only as the aggregate did the problem surface.

 

I found this post where someone had a similar issue: http://forum.hibernate.org/viewtopic.php?p=2394781. That and the forthcoming book NHibernate in Action from Manning got me thinking and I finally deduced the problem.

I must say this one was not obvious to someone just learning NHibernate. I lost a good 12 hours of effort both in trying to discover an answer and in simply trying to work my way around the problem.

 

Here's my mapping file: [I swear I'm switching to attributes first chance I get, but I learned the Xml mapping and time doesn't permit the change at this point]

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
    schema="TestDB.dbo"   
    namespace="Domain.Foo"
    >
  <class name="Domain.Foo.ProfileP, Domain" table="ProfileP" lazy="false" >
    <id name="ID" column="ID" type="Int32" unsaved-value="0">
      <generator class="native" />
    </id>
    <property name="ProfileId" column="profileId" type="Int32" />
    <property name="PaymentId" column="paymentId"   type="Int32"  insert="false" update="false" />
    <property name="Status" column="status"    type="string" length="10" />
    <many-to-one name="PaymentS" class="Domain.Foo.Sub, Domain" column="paymentId" cascade="save-update" not-null="true"  />
  </class>
</hibernate-mapping>

 

The problem is the line in red. The PaymentID is the ID value of the PaymentS class in the Domain.Foo.Sub namespace. So, NHibernate already knew the ID value and was using it in the update/save queries. In effect it was declared twice in the mapping file: once explicitly and once implicitly via the many-to-one relationship. The fix was to add insert="false" and update="false" to the paymentId property.

I ended up purchasing the NHibernate in Action book via the early access program. So far I am pleased with the purchase. The book has shed light on a lot of pieces of information that were unclear to me. Getting concise and complete information on NHibernate seems to be a lot harder than I would have thought.

2 comment(s)

Rich wrote on January 23, 2008

Bless you. You've just saved me another 12 hours!

Tim wrote on January 23, 2008

Rich,

Glad I could help.