【问题标题】:Entity Framework - Update/add value to existing value实体框架 - 将值更新/添加到现有值
【发布时间】:2017-01-24 23:01:47
【问题描述】:

在实体框架中是否可以向数据库中的现有值添加值? 目前我有这个:

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 解决了这个问题,但我正在寻找更好的实现。

提前致谢。

【问题讨论】:

  • 您使用的是哪个版本的 EF?
  • @MikeMazmanyan 你好,6.1.1

标签: c# entity-framework


【解决方案1】:

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

安装并编写:

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

【讨论】:

    【解决方案2】:

    EntityFramework Extended (6.1) 的当前版本已弃用已接受答案中指示的重载。现在应该将过滤和实际更新分开。这是一件好事,因为过滤可以很容易地动态构建。

    对于实际问题,查询应如下所示:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-29
      • 1970-01-01
      • 2018-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多