views:

23

answers:

1

I have a schema similar to the standard Product / OrderDetails / Order setup. I want to delete a single Product and cascade delete all OrderDetails which reference that product.

Assuming that I've thought this through from the business rules perspective, what's the most elegant way to handle that with Entity Framework 4?

+1  A: 

First thing is first:

Is there any reason on delete cascade at the database level won't work?

If that's really not a possibility, you could try the following:

Since ObjectContext doesn't have a DeleteAll style method...you could always implement your own:

public static void DeleteAll(this ObjectContext context, 
    IEnumerable<Object> records)
{
    foreach(Object record in records)
    {
        context.DeleteObject(record);
    }
}

Then you could write something like (probably in a Repository):

context.DeleteAll(context.OrderDetails.Where(od => od.Product == product));

Or, to be a little cleaner:

var toDelete = context.OrderDetails.Where(od => od.Product == product);

context.DeleteAll(toDelete);
Justin Niessner
Your idea in comments is cleaner than your answer. :) The EF should notice the cascade and "just work." http://blogs.msdn.com/alexj/archive/2009/08/19/tip-33-how-cascade-delete-really-works-in-ef.aspx
Craig Stuntz
@Craig I only posted the answer because I didn't get any response to my comments. I'll update my post.
Justin Niessner
Thanks - I think the edit to use on delete cascade if possible, otherwise manually delete cascading relationships sums this up well.
Jon Galloway