BennoDual
BennoDual

Reputation: 6259

Merge an existing Object which reference a new one

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.

Upvotes: 0

Views: 891

Answers (2)

Mr Mush
Mr Mush

Reputation: 1538

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.

Upvotes: 2

Anton
Anton

Reputation: 1583

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

Upvotes: 1

Related Questions