Reputation: 36081
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.
Upvotes: 0
Views: 250
Reputation: 4184
(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;
}
}
Upvotes: 3