webworm
webworm

Reputation: 11019

Updating a set of records in LINQ - All at once

I have several records that all need to be updated to the same value. If I was just using ADO.NET I could just call a stored procedure that updated them all at one ...

UPDATE myTable
SET myColumn = "XXXXXX"
WHERE filterColumn == 'YYY'

But since I am using Entity Framework I am wondering if their was a similar way to update a set of records at once without having to loop through each of the values and set them individually? Currently I am using..

from s in myTables
where s.filterColumn == 'YYY'
select s;

var results = s.ToList();

foreach (i in results){
  s.myColumn = "XXXXXX"
}

Is there a way to set the values all at once as in SQL?

I am using Entity Framework v6.1

Upvotes: 1

Views: 99

Answers (2)

Richard Deeming
Richard Deeming

Reputation: 31198

The Entity Framework Extended Library includes batch update / delete functionality:
https://github.com/loresoft/EntityFramework.Extended

myTables.Update(
    s => s.filterColumn == "YYY",
    s => s.myColumn = "XXXXXX");

NB: This currently only supports SQL Server and SQL CE, although there is a pull request to add MySQL support.

Upvotes: 2

tsuta
tsuta

Reputation: 357

You can still execute sql command when using Entity Framework. Here is how to do it.

dbContext.Database.Connection.Open();
var cmd = dbContext.Database.Connection.CreateCommand();

cmd.CommandText = @"UPDATE myTable
SET myColumn = @myColumn
WHERE filterColumn = @filterColumn";

cmd.Parameters.Add(new SqlParameter("myColumn", "XXXXXX"));
cmd.Parameters.Add(new SqlParameter("filterColumn", "YYY"));
cmd.ExecuteNonQuery();

Upvotes: 3

Related Questions