How to delete all the related entities?

With Northwind, how to delete all the orders of a customer?

You can do this:

foreach (var o in customer.Orders.ToArray())


but in this case, you will only delete the orders loaded in the context.

To delete all the DB customer orders, you can do this:

foreach (var o in customer.Orders.CreateSourceQuery())


This code will load all the customer orders and will delete each of them.

Now, how to delete all the related entities with no information about the entity?

You can do this:

public static void DeleteRelatedEntities(this EntityObject entity, ObjectContext context)


    foreach (var relatedEntity in (((IEntityWithRelationships)entity).RelationshipManager.GetAllRelatedEnds().SelectMany(re => re.CreateSourceQuery().OfType<EntityObject>()).Distinct()).ToArray())



This entry was posted in 7671, 7674. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *