EntityFramework.Extended 实现 update count+=1

简介:

在使用 EF 的时候,EntityFramework.Extended 的作用:使IQueryable<T>转换为update table set ...,这样使我们在修改实体对象的时候,避免先查询再修改,而是直接 Update,大致写法:

IQueryable<Entity> entities = _entityRepository.GetAll();
entities = entities.Where(x => x.Id == 1);
await entities.UpdateAsync(x => new Entity { Count = 666 });

但有时候,我们还有一种操作,就是在实体属性值的基础上,进行加减操作,不要被上面的new Entity吓到(误以为只能赋新值),其实用 EntityFramework.Extended 实现很简单,代码示例:

IQueryable<Entity> entities = _entityRepository.GetAll();
entities = entities.Where(x => x.Id == 1);
await entities.UpdateAsync(x => new Entity { Count = x.Count + 1 }); //在这里。

生成的 SQL 代码:

UPDATE [dbo].[Entity] SET 
[Count] = [Count] + 1  
FROM [dbo].[Entity] AS j0 INNER JOIN (
SELECT 
    [Extent1].[Id] AS [Id]
    FROM [dbo].[Entity] AS [Extent1]
    WHERE (1 =  CAST( [Extent1].[Id] AS int)) AND (1 = [Extent1].[Id])
) AS j1 ON (j0.[Id] = j1.[Id])

稍微有点复杂,如果去掉INNER JOIN多余代码就好了。




本文转自田园里的蟋蟀博客园博客,原文链接:http://www.cnblogs.com/xishuai/p/entityframework-extended-update-count.html,如需转载请自行联系原作者

相关文章
|
8月前
【开发专题_02】Executing an update/delete query
【开发专题_02】Executing an update/delete query
76 0
SQLSTATE[42S02]: Base table or view not found: 1146 Table ‘thinkphp.test‘ don‘t exsit
SQLSTATE[42S02]: Base table or view not found: 1146 Table ‘thinkphp.test‘ don‘t exsit
382 0
|
数据库
解决which is not functionally dependent on columns in GROUP BY clause;...sql_mode=only_full_group_by
解决which is not functionally dependent on columns in GROUP BY clause;...sql_mode=only_full_group_by
309 0
|
关系型数据库 MySQL 数据库
View ‘information_schema.SCHEMATA‘ references invalid table(s) or column(s) or function(s) or define
View ‘information_schema.SCHEMATA‘ references invalid table(s) or column(s) or function(s) or define
252 0
|
SQL 关系型数据库 MySQL
[Err] 1294 - Invalid ON UPDATE clause for 'comment_time' column【详细解决办法】
[Err] 1294 - Invalid ON UPDATE clause for 'comment_time' column【详细解决办法】
749 0
[Err] 1294 - Invalid ON UPDATE clause for 'comment_time' column【详细解决办法】
|
关系型数据库 MySQL 数据库
MySQL问题解决:Cannot delete or update a parent row: a foreign key constraint fails
MySQL问题解决:Cannot delete or update a parent row: a foreign key constraint fails
1516 0