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())

    context.DeleteObject(o);


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())

    context.DeleteObject(o);


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())

            context.DeleteObject(relatedEntity);

}

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

Leave a Reply

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


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>