在SubSonic中保存相关对象

时间:2009-05-14 13:38:09

标签: subsonic

我有2个表,Order和OrderItem,它们有1-many关系。

当我在前端添加新订单时,如何创建关系。 E.g。

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


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

我如何设置关系,以便在将它们保存到数据库时,它们将存储正确的外键值,这些内容与

一致。
item.setParent(order);

编辑:

我尝试使用

order.OrderItemRecords().Add(item);

但更新数据库时仍然出现错误。

1 个答案:

答案 0 :(得分:3)

(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

请记住在事务中包含并调用save方法将此信息提交到数据库。您将在项目中添加对System.Transactions命名空间的引用,然后在您的类中引用。

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;
        }
    }