EntityFramework.Extended 实现 update count+=1

时间:2021-06-26 00:06:49

在使用 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多余代码就好了。