Question

I use EntityFramework 4.1.

What I want to achieve is, whenever SaveChanges method is called on entities that are FooEntity, first I want to UPDATE those entities and then DELETE after.

I try to override the default behaviour as below, but I can't achieve what I want: It updates on the Db. but not DELETES.

How can I achieve this?

public override int SaveChanges()
        {
            var entitiesMarkedAsDelete = ChangeTracker.Entries<FooEntity>()
                                    .Where(e => e.State==EntityState.Deleted);

            foreach (var e in entitiesMarkedAsDelete)
            {
                e.State = EntityState.Modified;
            }

            base.SaveChanges(); // To enforce an UPDATE first

            // Now, I try to re-mark them to DELETE
            foreach (var e in entitiesMarkedAsDelete)
            {
                e.State = EntityState.Deleted;
            }

            base.SaveChanges(); // And hope that they will be deleted

            // RESULT: 1st call of base.Savechanges() updates the entities
            //       but the 2nd call of base.Savechanges() does not make any changes on the UPDATED 
            //      entities -and they are NOT DELETED.

        }
Was it helpful?

Solution

I think you are being fooled by the lazy nature of LINQ here.

The sequence you create here:

var entitiesMarkedAsDelete = ChangeTracker.Entries<FooEntity>()
                             .Where(e => e.State==EntityState.Deleted);

.. is being evaluated each time it is being iterated, so the second time you foreach over it, you don't actually get any results back, since there are no entities in the deleted state anymore.

So to fix this, you simply have to pipe the sequence into fx. a list, by calling .ToList on it:

var entitiesMarkedAsDelete = ChangeTracker.Entries<FooEntity>()
                             .Where(e => e.State==EntityState.Deleted).ToList();

That way both foreach statements will iterate over the same entities, and they should be deleted properly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top