What I want to achieve is the simple sql query: UPDATE TABLE SET COLUMN = COLUMN + 1
Is there a way to make it happen without loading all records (thousands) to memory first and loop through each record to increment the column and then save it back?
EDIT
I tried raw sql and it worked. I have to decide the sql provider from the connection string and the database schema name from the connection context. After that, I will use the corresponding sql query to update the table.
For SQL, it looks like UPDATE schemaname.TABLE SET COLUMN = COLUMN + 1. for POSTGRESQL, I have to double quote schema name, table name and column name: UPDATE "schemaname"."TABLE" SET "COLUMN" = "COLUMN" + 1.
We have to use the SET keyword in the UPDATE command for modifying the value of the columns. WHERE clause specifies which row you want to change.
In such a case, you can use the following UPDATE statement syntax to update column from one table, based on value of another table. UPDATE first_table, second_table SET first_table. column1 = second_table. column2 WHERE first_table.id = second_table.
The UPDATE command in SQL is used to modify or change the existing records in a table. If we want to update a particular value, we use the WHERE clause along with the UPDATE clause. If you do not use the WHERE clause, all the rows will be affected.
Here is the solution. You can use the following code:
context.Table.Where(x => x.Field1 > 0).Update(y => new Table { Field2 = y.Field2 + 1 });
hope that it helps.
With pure EF, you are right: you have to load the entities one by one, set the property, and save. Very inefficient.
The 2 alternatives that I know of are:
Quote from their main page:
Batch Update and Delete
A current limitations of the Entity Framework is that in order to update or delete an entity you have to first retrieve it into memory. Now in most scenarios this is just fine. There are however some senerios where performance would suffer. Also, for single deletes, the object must be retrieved before it can be deleted requiring two calls to the database. Batch update and delete eliminates the need to retrieve and load an entity before modifying it.
Deleting
//delete all users where FirstName matches
context.Users.Where(u => u.FirstName == "firstname").Delete();
Update
//update all tasks with status of 1 to status of 2
context.Tasks.Update(
t => t.StatusId == 1,
t2 => new Task {StatusId = 2});
//example of using an IQueryable as the filter for the update
var users = context.Users.Where(u => u.FirstName == "firstname");
context.Users.Update(users, u => new User {FirstName = "newfirstname"});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With