tags:

views:

158

answers:

3

I have 2 tables, Order and OrderItem, which have a 1-many relationship.

When I am adding a new order at the front end, how to I create the relationship. E.g.

(Order and OrderItem generated by SubSonic).
Order order = new Order();
//populate order details.


OrderItem item = new OrderItem();
//populate orderItem details.

How do I then set the relationship so that when I save them to the database they will store the correct foreign key values, something along the lines of

item.setParent(order);

EDIT:

I tried using

order.OrderItemRecords().Add(item);

but still getting error when I update DB.

+3  A: 
(Order and OrderItem generated by SubSonic).
Order order = new Order();
//populate order details.


OrderItem item = new OrderItem();
//populate orderItem details.

item.Order = order;   //THIS LINE SETS THE PARENT OBJECT TO ABOVE ORDER

Just remember to wrap up in a transaction and call the save methods to commit this info to your database. You will have add a reference to the System.Transactions namespace in your project and then reference in your class.

e.g

   using (TransactionScope scope = new TransactionScope())
    {
        try
        {
            Order order = new Order();
            //populate order details.
            order.Save(); //Commit to DB


            OrderItem item = new OrderItem();
            //populate orderItem details.

            item.Order = order;   //THIS LINE SETS THE PARENT OBJECT TO ABOVE ORDER

            item.Save();  //Commit to DB

            //complete you transaction
            scope.Complete();

        }
        catch (System.Data.SqlClient.SqlException ex)
        {
            throw ex;
        }
    }
littlechris
A: 

What is the difference betwen: .Save() and .Update() and .Add()

Shuaib
Since you asked this as a new question (as is appropriate) and got an answer there, you could delete this post. Here it doesn't really help anybody searching for answers to *this* question.
sth
A: 

Is there a way to update both tables with one save method?

Matt
Better ask this as a new question, not here in an old thread. More people would see it and try to help you. The "Ask Question" button is in the top right of the page...
sth