Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Entity Framework generate an UPDATE ... WHERE statement in SQL?

Building a data access layer for an internal enterprise MVC application with Entity Framework and the repository pattern. In some cases, I need to update, say, 100k rows in a table with 100 million or so rows in a SQL Server 2008 R2 database.

I am using EF6, targeting an existing legacy database we are refactoring. I am new to Entity Framework, but have much experience with SQL Server.

No matter how I seem to structure my update statement, when I run a profiler, I see 60k individual updates by ID. This can take up to 5 minutes to run. However, I have say a "batch number" that is indexed for a bunch of these records. Is there any way to UPDATE these records with a single where clause generated from EF? My solution has been to just write a simple sp that I then have EF call.

like image 532
jkerak Avatar asked Dec 04 '15 18:12

jkerak


People also ask

Can we use update with WHERE clause?

Notice the WHERE clause in the UPDATE statement. The WHERE clause specifies which record(s) that should be updated. If you omit the WHERE clause, all records in the table will be updated!

How do I update values in Entity Framework?

This can be achieved in several ways: setting the EntityState for the entity explicitly; using the DbContext. Update method (which is new in EF Core); using the DbContext. Attach method and then "walking the object graph" to set the state of individual properties within the graph explicitly.

What will happen if WHERE clause in update statement will be omitted?

If you do not use WHERE clause in UPDATE statement, all the records in the table will be updated.


1 Answers

Entity Framework in its current version does not support bulk operations in the sense that you are wanting it to. Each update or delete will be one individual transaction per record. To avoid this, you can run SQL directly from Entity Framework if you do not want to go through the hassle of creating a stored procedure (though, they are pretty easy to get up and going)

using (var context = new MyDbContext())
{
    context.ExecuteStoreCommand("Update MyTable Set Value = {0} Where SomeColumn = {1}", 
                                updateValue, queryValue);
    context.ExecuteStoreCommand("Delete From MyTable Where value = {0}", 
                                myValueToQueryBy);
}

Note the use of the parameter by using syntax that looks very similar to a string.Format(). Please see the MSDN for more information.

like image 148
Tommy Avatar answered Oct 21 '22 23:10

Tommy