Knight Data Access Layer
Save with Children
Basic Tasks C# > Saving Data > Save with Children

Normal save methods do not save parents and children.  Use the SaveWithChildren to save all parents and children.  It will recursively parse the object tree, properly saving parents before saving children.  It can handle many to many relationships.  The save is automatically wrapped in a transaction.

 

//Get the current instance of the helper

IDataHelper db = DataHelper.SessionFactory();

 

//Create an Order with a Parent and Children

Order order = new Order();

order.Buyer = new Person();

order.Buyer.FirstName = "John";

order.Buyer.LastName = "Smith";

order.Buyer.DateCreated = DateTime.Now;

order.OrderDetails = new List<OrderDetail>();

 

OrderDetail detail1 = new OrderDetail();

detail1.Item = new Product();

detail1.Item.ProductName = "Wizard";

detail1.Item.Cost = 29.98M;

detail1.Quantity = 2;

detail1.Order = order;

order.OrderDetails.Add(detail1);

 

OrderDetail detail2 = new OrderDetail();

detail2.Item = new Product();

detail2.Item.ProductName = ".NET Caching Library";

detail2.Item.Cost = 199.95M;

detail2.Quantity = 1;

detail2.Order = order;

order.OrderDetails.Add(detail2);

 

//Save parents and children

db.SaveWithChildren(order);

 

//Reload the entire tree

Order orderCopy = db.LoadWithChildren<Order>(order.OrderId);