views:

20

answers:

1

If I have a Customers table linked to an Orders table, and I want to delete a customer and its corresponding orders, then I can do:

dataContext.Orders.DeleteAllOnSubmit(customer.Orders);
dataContext.Customers.DeleteOnSubmit(customer);

...which is great. However, what if I also have an OrderItems table, and I want to delete the order items for each of the orders deleted?

I can see how I could use DeleteAllOnSubmit to cause the deletion of all the order items for a single order, but how can I do it for all the orders?

+3  A: 

You might wish to consider using on delete cascade on the foreign key relationship in the database rather then using LINQ to do it. If you wish to use LINQ then

customer.Orders.ForEach(x => x.OrderItems.ForEach(y=> dataContext.OrderItems.Delete(y));
dataContext.Orders.DeleteAllOnSubmit(customer.Orders);
dataContext.Customers.DeleteOnSubmit(customer);

should do it but I haven't tested it.

stimms
+1 for that tip about Foreign key relationships Cascading.
Cyril Gupta
How would that be translated into SQL? It looks like it's going to create a loop, whereas I would have hoped a JOIN could be used?
Gary McGill
Also, you write "OrderItems.Delete" which seems different to the DeleteOnSubmit used on the other tables? Are the two compatible?
Gary McGill