实体框架通过将当前值增加1而不选择来更新一列 [英] Entity framework update one column by increasing the current value by one without select
问题描述
我想要实现的是简单的sql查询: UPDATE TABLE SET COLUMN = COLUMN + 1
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?
编辑
我尝试过原始的sql,它的工作。我必须从连接字符串和连接上下文中的数据库模式名称来决定sql提供者。之后,我将使用相应的sql查询来更新表。
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.
对于SQL,它看起来像UPDATE schemaname.TABLE SET COLUMN = COLUMN + 1 即可。
为POSTGRESQL,我必须双引号模式名称,表名和列名:更新schemaname。TABLESETCOLUMN=COLUMN+ 1 。 >
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.
推荐答案
这是解决方案。您可以使用以下代码:
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 });
希望它有所帮助。
这篇关于实体框架通过将当前值增加1而不选择来更新一列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!