views:

735

answers:

3

I have 2 Linq2Sql classes: Parent and Child. I want to do things like removing all children for a parent, or updating all child records. In SQL I would have written:

delete Child where ParentID = @p

or

update Child set Val = Val+1 where ParentID = @p

I can do this in Linq the brute force way inside the Parent class:

Children.ToList().ForEach(c => c.DeleteOnSubmit()); // DeleteOnSubmit is my own method

and

Children.ToList().ForEach(c => c.Val++);

But given Linq's inherent performance penalty on ForEach loops, this seems like a very inefficient way to do things. Is there some way of achieving the desired end that will fire off exactly one query?

+5  A: 

For these cases you can use the DataContext.ExecuteCommand method to directly execute SQL on your database. For example:

dataContext.ExecuteCommand("delete Child where ParentID = {0}", parentId);
Konamiman
Ugh, that's ugly. Doesn't using literal SQL defeat half the purpose of using Linq?
Shaul
@Shaul, For the most part, yes, but LINQ-To-SQL doesn't support mass update/delete, so that's your option. Another option would be a stored procedure.
Eclipsed4utoo
Oh well, if there's no other alternative, I guess you get answer credit...
Shaul
Sometimes we *need* to use ugly code. You can unuglify it a little by confining it inside a method, `DeleteChilds(parentId)`or the like.
Konamiman
Sorry about withdrawing the answer credit - but take a look at Terry Aney's solution to this problem, and I think you'll agree this is a freakin' brilliant (and elegant) approach!
Shaul
+3  A: 

look at this link : It's using ExpressionTree : http://www.aneyfamily.com/terryandann/post/2008/04/Batch-Updates-and-Deletes-with-LINQ-to-SQL.aspx

pdiddy
+1 Wow, this is a great link! I'm on the verge of changing my mind about answer credit...
Shaul
Yep, Terry Aney's solution rocks! Answer credit to you!
Shaul
+1  A: 

Take a look to http://magiq.codeplex.com mass operation with linq.

ivos
looks interesting, thanks
Shaul