Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run a mass update/delete query in Linq?

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?

like image 478
Shaul Behr Avatar asked Dec 23 '09 12:12

Shaul Behr


People also ask

How do I delete multiple records in LINQ?

You can drag the SPROC to your DBML file and it will generate a rich method in your databasecontext class. Show activity on this post. First, you can find a list of the items you want to delete.

How do I delete a record in LINQ query?

You can delete rows in a database by removing the corresponding LINQ to SQL objects from their table-related collection. LINQ to SQL translates your changes to the appropriate SQL DELETE commands. LINQ to SQL does not support or recognize cascade-delete operations.

How do you update a record in LINQ?

You can update rows in a database by modifying member values of the objects associated with the LINQ to SQL Table<TEntity> collection and then submitting the changes to the database. LINQ to SQL translates your changes into the appropriate SQL UPDATE commands.

How do I bulk update entity framework?

Extensions Update method. The Update method is able to bulk update for a set of records with same set of update values. Records. Update(new => Record { Quantity = 100 });


1 Answers

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);
like image 52
Konamiman Avatar answered Oct 04 '22 16:10

Konamiman