开发者

How can I do more than one level of cascading deletes in Linq?

开发者 https://www.devze.com 2022-12-24 03:04 出处:网络
If I have a Customers table linked to a开发者_如何学Pythonn Orders table, and I want to delete a customer and its corresponding orders, then I can do:

If I have a Customers table linked to a开发者_如何学Pythonn 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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号