The problem is that you have a graph (directed graph) of objects, referencing eachother. What you want is remove a couple of these objects from the graph. It's not hard to create a list of entities in the graph, you can use the ObjectGraphUtils class for that for example. The thing is that you have to reset the references in OTHER objects to the objects you want to remove otherwise the entities won't be removed from the graph.
I think you can use a trick. If I have an order instance myOrder and a customer instance myCustomer, this is true:
myOrder.Customer = myCustomer;
after this, this line returns true
myCustomer.Orders.Contains(myOrder);
and vice versa:
myCustomer.Orders.Add(myOrder);
-> this is true
myOrder.Customer==myCustomer;
Now, let's say myOrder is the entity you want to remove and you have a reference to it. This means that it should be removed from myCustomer.Orders. But you only have a reference to myOrder. Now, you can do:
myOrder.Customer = null;
this will remove myOrder from myCustomer.Orders.
But, this is of course not really scalable among an unknown set of entities. What you can do is calling GetRelatedData() on all entities you want to remove.
This gives you a dictionary back with as key the name of the property (field) mapped onto the relation and as value the related entity or the collection of related entities. I'll now assume you haven't hidden any relations from one side.
What you'll now do is this:
// for adapter. For selfservicing, replace IEntity2 with IEntity
foreach(IEntity2 entity in entitiesToDelete)
{
Dictionary<string, object> relatedData = entity.GetRelatedData();
foreach(KeyValuePair<string, object> pair in relatedData)
{
IEntity2 relatedEntity = pair.Value as IEntity2;
if(relatedEntity==null)
{
// not an entity or null
continue;
}
relatedEntity.UnsetRelatedEntity(entity, pair.Key);
entity.UnsetRelatedEntity(relatedEntity, pair.Key); // not necessary for 1:n/m:1 relations
}
}
Not tested, but it should work. The last line has a comment for 1:n/m:1 relations. The call is redundant for these relations, as the first call already unsets the reference. You can avoid that call by calling entity.GetAllRelations() and traverse the relations, checking the mappedfieldname if it matches pair.Key, and then check the relation type.