1

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

webworm
  • 10,587
  • 33
  • 120
  • 217

2 Answers2

3

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();
tsuta
  • 357
  • 4
  • 12
2

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.

Richard Deeming
  • 29,830
  • 10
  • 79
  • 151