GrayFox
GrayFox

Reputation: 1089

EF 6 deletes object from collection when marked as deleted

I follow this tutorial:

EF 6 disconnected scenario

    foreach (var foo in item.Foos)
    {
        if (foo.State == PocoState.Deleted)
        {
            ctx.Entry(foo).State = EntityState.Deleted;
        }
    }
    ctx.SaveChanges();

But I always get an InvalidOperationException because the 'foo' is deleted from item.Foos before calling ctx.SaveChanges();

Upvotes: 0

Views: 44

Answers (1)

Fabio
Fabio

Reputation: 11990

You can't delete from a list while you are iterating that list. A ToList will solve the problem because you will iterate a "copy" instead of the list itself.

 foreach (var foo in item.Foos.ToList())
 {
    if (foo.State == PocoState.Deleted)
    {
       ctx.Entry(foo).State = EntityState.Deleted;
    }
 }
 ctx.SaveChanges();

Upvotes: 3

Related Questions