Spiderman
Spiderman

Reputation:

Saving Parent and children

I have a couple of tables in my schema with PK and FK relationships. I have created the DAL using the SubSonic generator. If I create a new parent and its children, how should I save both? Separately or in one shot?

e.g.

Parent.Save();  
ChildCollection.SaveAll();

I tried the above, but it does not work because ChildCollection does not have its parent's ID. Is it that I have to assign parent IDs for each child myself or is there an option to save it all in one shot?

Upvotes: 2

Views: 156

Answers (2)

runxc1 Bret Ferrier
runxc1 Bret Ferrier

Reputation: 8233

Assumption: That your Primary Keys are auto generated by your Data Base. If so, what you will need to do first is Save() the parent and then populate the ParentID property in each of the objects in your ChildrenCollection. Once you have done that, you will be able to Save() your ChildrenCollection.

        Parent.Save();
        ChildCollection.ForEach(x => x.ParentID = Parent.ParentID);
        ChildCollection.SaveAll();

Upvotes: 1

TheVillageIdiot
TheVillageIdiot

Reputation: 40537

You can use partial classes with custom overload of save function to provide the desired functionality.

public partial class Class1
{
    public void Save(bool childern)
    {
        Save();

        if (childern)
        {
            //based on primary/foreign key SubSonic provides
            //methods to fetch child collections related to
            //this (primary key) table.
            ChildernCollection col = Childerns();

            col.SaveAll();
        }
    }
}

Upvotes: 0

Related Questions