If you’re like me, you’ve often grumbled about the inefficiency of deleting related records from a child entity via EF. For example:
In the above example, if I try to delete the Employee Entity that has a key of 1, EF will throw a “Foreign Constraint Violation” exception (as it should). And, yes, I know you can set the child table to cascade deletes in SQL Server and that this should work within EF, but I’ve never gotten it to work reliably. Usually, I’ve just written a method which manually deletes the child rows, to wit:
While the code above works, it’s complicated by a few factors: First, I just hate using old C-style for loops: They’re clumsy and hard to read; second (and this is a much bigger deal) note the strange way the deletion occurs (via Remove, instead of DeleteObject) and that the count incrementor variable is decremented after each deletion. This is necessary because you cannot iterate with incrementation because the Remove statement changes the count of affected child records, which causes another exception. Futher confusion and ugliness ensues. In short, this code is too hard to maintain and support.
But with LINQ’s ForEach(), I can accomplish the deletes in one simple line of code:
The line of code: svr.Storages.ToList().ForEach(s => db.Storages.DeleteObject(s)) does everything the for loop did, in a much more succinct and readable way. So FYI…LINQ is cool.