LINQ’s ForEach() Method

If you’re like me, you’ve often grumbled about the inefficiency of deleting related records from a child entity via EF.  For example:

 Entity Relationship Diagram

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:

Old, Ugly Code

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:

New, Pretty 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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s