我不确定这是关于 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 whenSaveChanges()
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 returnedEntityEntry
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/