I try not to have my business logic know the inner workings of my data layer and vice versa.
But Entity Framework makes it difficult. I can paste into the collection (in my business layer) without reference to the ObjectContext:
order.Containers.Add(new Container { ContainerId = containerId, Order = order });
And it saves well when it comes time to do SaveChanges() in the data layer.
But to remove an item from the collection, I need a reference to the ObjectContext. (I do # 1 in this guide to removing EF objects .) If I just do this:
delContainers.ForEach(container => order.Containers.Remove(container));
Then, when I call SaveChanges() , I get an exception telling me that I need to delete the object, as well as the link.
So my options, as I see it, are:
- Passing a delegate into my business logic, which will call the ObjectContext Delete method of an Entity Framework object.
- Or (I hope) find a way to get all entities that have their link removed and actually delete them. (right before calling
SaveChanges() in my data layer.)
Does anyone know how to do this?
UPDATE:
I tried this:
// Add an event when Save Changes is called this.ObjectContext.SavingChanges += OnSavingChanges;
...
void OnSavingChanges(object sender, EventArgs e) { var objectStateEntries = ObjectContext.ObjectStateManager .GetObjectStateEntries(EntityState.Deleted); foreach (var objectStateEntry in objectStateEntries) { if (objectStateEntry.IsRelationship) {
But none, although I removed the link, the set of deleted items is empty.
(I tried to look at all the elements too, and my relationship is not there. Obviously, there is something fundamental that I'm not talking about ObjectStateManager about.)