tags:

views:

273

answers:

2

Hibernate version: 2.0.1GA

I'm trying to add a single record in two tables. The tables are related. I have a beginner's knowledge of NHiberate so I'm hoping there's a better way to do this.

Presently, I am under the belief that the only way I can get the ID of a newly-added record is to perform a SaveOrUpdate; then the object's ID field gets set (since I'm using autoincrement with SQL Server 2005 Express).

In order to add a record in a related table, I have to set the ID field of its parent. Here's what I'm doing now:

transaction = session.BeginTransaction();

Contact myContact = new Contact();

myContact.Company = "ABC Company"; myContact.Notes = "test";

session.SaveOrUpdate(myContact);

Address myAddress = new Address(); myAddress.IdContact = myContact.Id; myAddress.City = "Any City"; myAddress.State = "XX"; myAddress.Zip = "12345";

session.SaveOrUpdate(myContact);

// Commit transaction transaction.Commit();

Note that ADDRESS is related to CONTACT. 1 CONTACT per MANY ADDRESSES.

In order to add the ADDRESS record, I have to have the corresponding CONTACT ID and I believe I can only get that AFTER I create the CONTACT record, hence my use of "SaveOrUpdate" twice.

Better way out there?

Thanks!

+2  A: 

There's a far easier way.

First, add the Address object in to your Contact object

public class Contact
{
   public Contact(){}
   private IList<Address> _addresses;
   public IList<Address> Addresses
   {
          get
          {
                 if(_addresses == null) _addresses = new List<Address>(); 
                 return _addresses 
          }
          set
          {
                 _addresses = value;
          }
   }

Then in your mapping file map the property Address to the address table in your database.

Something like this in your mapping file for Contact:

<bag name="Addresses" cascade="all-delete-orphan" lazy="false">
  <key column="Address_FK" />
  <one-to-many class="DomainModel.Address, DomainModel" />
</bag>

Then set the cascade property of the Contact class to:

  default-cascade="save-update"

Now, when you populate the Address object in Contact, and save the Contact object, the Address object collection will persist automagically.

I can do fuller examples if required.

DavidWhitney
A: 

Thank you! I will give this a try and let you know.

Got another question, but I will post anew.

Donna