Thursday, 14 May 2009

Subsonic Parent -> Child saving

How to save subsonic objects to the db that have FK values needing set.

Here's an example that also uses a transaction. Please note that you will have add a reference to the System.Transactions namespace in your project and then reference in your class.



   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;

        }

    }


No comments:

Free Hit Counter