entity-framework-core - Entity Framework Core 更新未更改的字段

标签 entity-framework-core audit.net

我不确定这是关于 Entity Framework 的问题,还是关于 audit.net 库如何工作的问题,但我猜这与我如何使用 EF 执行更新有关。我的目标是仅捕获记录的实际更改,但它会将所有内容都捕获为更改,即使旧值和新值相同。

基本上是为了尽可能地简化它,如果我这样做

var existing = context.Appl.FirstOrDefault(a => a.Id == id);
context.Appl.Update(existing);
context.SaveChanges();

(什么都没变)

Audit.Net 更改日志说每个字段都已更改,看起来像
   "Changes": [
      {
        "ColumnName": "FOO",
        "OriginalValue": "",
        "NewValue": ""
      },
      ..... many more

最佳答案

My goal is to capture only actual changes to the record



那么你不应该使用 Update方法。

根据Update方法 documentation :

Begins tracking the given entity in the Modified state such that it will be updated in the database when SaveChanges() is called.

All properties of the entity will be marked as modified. To mark only some properties as modified, use Attach(Object) to begin tracking the entity in the Unchanged state and then use the returned EntityEntry to mark the desired properties as modified.


Update的主要使用案例方法是在使用 Disconnected Entities 时执行所谓的强制更新。 .由于您的 existing实体是从上下文中检索的(或者换句话说,由上下文跟踪),因此您需要的只是设置新值。更改跟踪器将检测是否有实际的属性更改并发出 UPDATE仅包含修改值的命令(如果所有当前值都等于原始值,则根本没有 UPDATE 命令)。

关于entity-framework-core - Entity Framework Core 更新未更改的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50353162/

相关文章:

postgresql - ALTER TYPE ... ADD 无法在事务 block 内运行 - Entity Framework

c# - Audit.NET动态获取数据库凭据

c# - Audit.Net,-即使抛出异常也需要正确的审计

c# - 当我无权访问 HttpContext 时,如何填充我的审计日志 UserId 字段?

entity-framework - Audit.NET Entity Framework 审核两个表的同一条目

.net-core - 将 Audit.NET SqlDataProvider 与 Azure SQL 和托管标识结合使用

entity-framework-core - EF核心5 : Include With Where Statement Followed by ThenInclude -- Inheritance Problem

.net-core - 如何使用 Entity Framework Core 更新记录?

c# - CS0311 C# 该类型不能用作泛型类型或方法中的类型参数 'TContext'。 Entity Framework 核心

c# - EF Core,按 UTC 日期按月和年分组