0

I load a Contact-objekt from the database. The Object Contact has a one-to-many mapping to ContactSecurity:

    <set name="ContactSecuritys" lazy="true" inverse="true" cascade="none" >
        <key>
            <column name="ContactId"/>
        </key>
        <one-to-many class="ContactSecurity"/>
    </set>

Now, I try to do:

contact.ContactSecuritys.Add(new ContactSecurity(Guid.NewGuid()));
Session.Merge(contact);

But this is throwing an TransientObjectExcpeption 'object is an unsaved transient instance - save the transient instance before merging: Prayon.Entities.ContactSecurity'

I have also tried

contact.ContactSecuritys.Add(new ContactSecurity(Guid.NewGuid()) {Contact = contact});
Session.Merge(contact);

What I am doing wrong? - Does I have to extra-save the new ContactSecurity-Object with referenced Contact before merging the contact? - Or is there a simpler way to do this?

Thanks for any help.

svick
  • 236,525
  • 50
  • 385
  • 514
BennoDual
  • 5,865
  • 15
  • 67
  • 153

2 Answers2

2

Your problem is not caused by the ContactSecurity. You should change your cascade settings to - cascade="save-update" at least, to allow the main class to update and insert other objects in its properties.

Mr Mush
  • 1,538
  • 3
  • 25
  • 38
1

I think it because "ContactSecurity" is a new transient object. If an entity with the same identifier has already been persisted, you can use "session.Merge()", but there is no any entity with a such identifier. You may use "session.Persist(ContactSecurity)" to attach a transient object to a Session.

var contactSecurity = new ContactSecurity(Guid.NewGuid());
Session.Persist(contactSecurity);

contact.ContactSecuritys.Add(contactSecurity);
Session.Merge(contact);

In general I don't understand why are you using "session.Merge()". If entity "contact" is a persistent object you can use "session.Flush()" in the end of transaction, and don't call "session.Merge()":

var contactSecurity = new ContactSecurity(Guid.NewGuid());
Session.Persist(contactSecurity);
contact.ContactSecuritys.Add(contactSecurity);
Session.Flush();
Anton
  • 1,583
  • 12
  • 17
  • With session.Persist() I have the problem, that there are not-null properties in contactSecurity - this will be set in a Save-Event. – BennoDual Mar 10 '12 at 12:14