gpt4 book ai didi

c# - Entity Framework - 更新/增加现有值(value)

转载 作者:太空宇宙 更新时间:2023-11-03 23:24:58 25 4
gpt4 key购买 nike

在 Entity Framework 中是否可以向数据库中的现有值添加一个值?目前我有这个:

var ent = this.repository.GetSingle(id);
var moreQuantity = 5; // This is calculated in application logic
ent.quantity = ent.quantity + moreQuantity;
this.repository.SaveChanges();

可以在单个数据库交互中做同样的事情吗?我的意思是在 SQL 中是这样的:

UPDATE table SET quantity = quantity + {moreQuantity} WHERE id = {id}

不使用 ExecuteSqlCommand 或 ExecuteStoreQuery。

我问这个问题的原因是因为我的应用程序中的 GetSingle 和 SaveChanges 之间有大量时间,所以我运行时遇到了一些并发问题。我设法用 RowVersion 和 ConcurrencyCheck 解决了它,但我一直在寻找更好的实现。

提前致谢。

最佳答案

有一个不错的图书馆EntityFramework.Extended

安装并写入:

context.repository.Update(e => e.id == id, e2 => new entity { quantity = e2.quantity + moreQuantity });

关于c# - Entity Framework - 更新/增加现有值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34135748/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com