NHibernate and adding new items with a composite collection to a child collection

advertisements

I have three classes that pose a problem when trying to add a new child.

They are:

 User {
        List attributesGroup>
 }

 AttributesGroup {
    attributesGroupId
    value
 }

 AttributesGroupId {
     attrName
     userId
 }

The mapping is:

<class name="AlternativeUserAttributes" table="`AlternativeUserAttributes`" lazy="true">
    <composite-id name="Id" class="Data.Entities.AlternativeUserAttributesId">
      <key-property name="AttributeName"  column="`attributeName`" type="string" />
      <key-many-to-one name="User" class="Entities.User" column="`userId`" />
    </composite-id>
    <property name="AttributeValue" column="`attributeValue`" type="string" />
    <many-to-one name="User" column="`userId`" cascade="none" not-null="true" />
  </class>

I can remove items and class SaveUpdate on the user class without issue, however when I try to add an item to the collection via:

 AlternativeUserAttributes aua = new AlternativeUserAttributes();
             aua.Id = new AlternativeUserAttributesId();
             aua.Id.AttributeName = name;
            aua.Id.User = curUser;
             aua.AttributeValue = value;
             aua.User = curUser;

        curUser.AlternativeUserAttributes.Add(aua);

I get an error about that the row count was expected to be 1 but was zero, and when I try to save only the AlternateUserAttributes as its self using Save, I get the this error: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index

Both attempts are yelding a INSERT for the new Item but i keep getting these errors. Is there anyone that can help?


I'm having a hard time following (SO mangled your post), but using a composite ID can cause this problem. Since the ID type is 'assigned' NHibernate has no idea how to tell if the object is transient or persisted.

https://www.hibernate.org/hib_docs/nhibernate/1.2/reference/en/html/example-parentchild.html

Go to section 17.4 for more information.

One solution is to use a version or timestamp field. I ended up implementing the base class that tracks persistence and using an interceptor.

I posted code here: How to save a child with assigned id in nhibernate

That said, if you are getting INSERTs then I'm not 100% sure this is the same problem.