Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bulk Update with LINQ to SQL

Tags:

linq-to-sql

Is there a way to do a bulk update on a collection with LINQ? Currently if I have a List<myObject> and I want to update column1 to equal TEST for every row in the List I would setup a foreach loop and then for each individual object I would set the value and then save it. This works fine but I was just wondering if there was some LINQ method out there where I could do something like myOject.BulkUpdate(columnName, value)?

like image 448
esastincy Avatar asked Aug 25 '11 15:08

esastincy


1 Answers

Your requirement here is entirely possible using Linq expressions and Terry Aney's excellent library on this topic.

Batch Updates and Deletes with LINQ to SQL

An update in the terms of the example you gave would be as follows:

using BTR.Core.Linq;
...

Context.myObjects.UpdateBatch
(
    Context.myObjects.Where(x => x.columnName != value),
    x => new myObject { columnName = value}
);

Edit (2017-01-20): It's worth nothing this is now available in the form of a NuGet package @ https://www.nuget.org/packages/LinqPost/.

Install-Package LinqPost
like image 99
Peter Majeed Avatar answered Oct 27 '22 03:10

Peter Majeed