Order of Insertion

Order of Insertion

Old forum URL: forums.lhotka.net/forums/t/2007.aspx


mharper posted on Tuesday, December 19, 2006

Does anyone know how CSLA handles this issue?  I have an editable root object named Apartment.  This object contains two child objects, Address & Features.  The Apartment object requires the identity key of the Address object; the Features object requires the identity of the Apartment object.  Since the children objects are saved first, how do I populate the Apartment Identity inside the Features object since the Apartment Identity has not be created at this point.  And if the items are flipped, I can not save Apartment without the Address Identity key. 

 

Thanks in advanced….

Michael

albruan replied on Thursday, December 21, 2006

I may be a bit confused, but from the way you describe things, it sounds as if the Address object should be the parent object with the Apartment object being both its child and the parent of the Features object.  That way, the primary id of the Address object is returned when it's persisted to the db.  The Address object's primary key is then used as the foreign key for the Apartment object and the Apartment object's primary key would then be the foreign key for the Features object.

Brian Criswell replied on Thursday, December 21, 2006

I would really recommend not altering your object structure to fit the database structure.

In most real world examples, the address is an attribute/extra piece of data for a building, person, shipment, etc.  This means that address is usually a child of a parent entity.

The way you make this work in this scenario is to just save the address first.  From your description, I am assuming you are using identity keys or something similar.  So the relevant parts of your two objects would look like this:

public class Address
{
    ...
    internal void Insert(SqlConnection cn)
    {
       // Set up command object and execute it
       // Retrieve the new id value
       _id = (int)cmd.Parameters["@Id"].Value;
    }
}

public class Apartment
{
    ...
    private override void DataPortal_Insert()
    {
       // Set up connection

       // Save address
       _address.Insert(cn);

       // Set up insert to data source, in this case a SQL server
       // Then add parameters
       cmd.Parameters.AddWithValue("AddressId", _address.Id);
       cmd.ExecuteNonQuery();

       // Save features
       _features.Insert(cn, this);
    }
}

Copyright (c) Marimer LLC