Thursday, 3 May 2012

WCF DeleteObject

Because Orders table has a constaint to Order_Details table, the latter has to be deleted also with related Order.
        private void btnDelete_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var custorder = lstOrders.SelectedItem;

                System.Type type = custorder.GetType();

                int orderid = (int)type.GetProperty("OrderID").GetValue(custorder, null);
                 
                Order odemo = ctx.Orders.Where(o => o.OrderID == orderid).ToList()[0];
                var odt = ctx.Order_Details.Where(od => od.OrderID == orderid).ToList();

                foreach(Order_Detail od in odt)
                        ctx.DeleteObject(od);

                ctx.DeleteObject(odemo);
                ctx.SaveChanges();
                MessageBox.Show("Deleted!");
                cmbCustomers_SelectionChanged(null, null);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: " + ex.ToString());
            }
        }

No comments:

Post a Comment