Problem with adding and deleting items to EnityCollection

Posts   
 
    
BertJ
User
Posts: 8
Joined: 12-Dec-2008
# Posted on: 12-Dec-2008 11:31:53   

Hi,

I think I have an easy question but I can't find a solution myself.

The problem is the following, I am adding and deleting items to an EntityCollection at the same time, when they are deleted they are added to the removedentitiestracker of the collection.

After adding and deleting the items I am saving the collection with a UnitOfWork:

            var vUnitOfWork = new UnitOfWork2();

            vUnitOfWork.AddForSave(Parent);

            foreach (Child vChild in Parent.Children)
            {
                if (vChild.Children.RemovedEntitiesTracker != null)
                {
                    vUnitOfWork.AddCollectionForDelete(vChild.Children.RemovedEntitiesTracker);
                }
            }

            // Commit the Unit Of Work
            vUnitOfWork.Commit(adapter, true);

I 've read in another thread that AddForDelete only works on non-new entities so the deleting of the items which are already in the database is not the problem.

The problem I have is that the items which I add and then delete are still added to the Database.

So for example: - there is one child in the database - I add two children in memory (count = 3) - I remove the one which is in the database (count = 2) - I remove one of the two children which are still in memory (count = 1)

When I save this collection with the code above I found two children in the database, the one which was already in the database is correctly deleted, but the unit of work still inserts the one which should not be inserted at all.

I am adding children like this:

                    new Child()
                        {
                            Parent = parent,
                        };

Can you help me please?

Thanks!

Grtz, Bert Janssens

Walaa avatar
Walaa
Support Team
Posts: 14993
Joined: 21-Aug-2005
# Posted on: 12-Dec-2008 12:12:24   

It seems that the collection of entities is attached to one or more related entities and when you remove entities from the collection, they are still accessible through the related entities, which is the main cause for the inserts since you are saving the graph recursively.

Please specify which runtime library instance you are using.

And please explain the graph of objects and their relations, and how you add and remove the entities to and from the collection.

BertJ
User
Posts: 8
Joined: 12-Dec-2008
# Posted on: 12-Dec-2008 12:22:46   

Hi thanks for the info,

I already solved it myself, the problem was that my Child itself had a relation to another entity

So my solution was: before the remove, set the FK to null and then remove