如何在调用`SaveChanges` 后获取`DbContext` 中已跟踪实体的先前状态。

huangapple go评论74阅读模式
英文:

How to get previous state of a tracked entity in dbcontext after savechanges

问题

当我们使用DbContext时,它会跟踪附加到其中的实体发生的更改。

如果您修改属性,会向ChangeTracker.Entries添加一个具有EntityState.Modified状态的条目,当您添加或删除实体时也会发生相同的情况,它们将以EntityState.Added或EntityState.Deleted状态发送到ChangeTracker;

按状态获取条目的一种方法:

private List<EntityEntry> GetChangesByType(params EntityState[] states)
{
     var entries = this.ChangeTracker.Entries();
     return entries.Where(x => states.Contains(x.State)).ToList();
}

我需要记录这些条目以及它们正在发生的操作,但是在添加实体的情况下,我不会有Id,因此我需要在记录之前执行savechanges,但是当调用savechanges时,它将所有已跟踪的条目移到EntityState.Unchanged状态,这样我无法知道这些条目的先前状态。

是否有一种方法可以获取先前的状态,或者有其他解决方案可以实现这一点?

英文:

When we are working with DbContext it tracks what happens to the entities attached to it.

If you modify a property, an entry will be added to ChangeTracker.Entries with EntityState.Modified, the same happens when you add or delete entites, they will be sent to ChangeTracker with a State EntityState.Added or EntityState.Deleted;

A way to get the entries by state:

private List&lt;EntityEntry&gt; GetChangesByType(params EntityState[] states)
{
     var entries = this.ChangeTracker.Entries();
     return entries.Where(x =&gt; states.Contains(x.State)).ToList();
}

I need to log these entries with the operation that is occurring to them, but In case of adding an entity I will not have the Id, so I need to perform a savechanges before log, but when savechanges in called, it moves all tracked entries to EntityState.Unchanged, by doing this I can't know the previous state of these entries.

Is there a way to get the previous state, or another solution to do this

答案1

得分: 2

SaveChanges之前捕获条目并在之后进行处理 - 它们将包含已更新的标识符。例如:

public override int SaveChanges()
{
    var entries = GetChangesByType(...);

    var result = base.SaveChanges();

    // 处理/记录这些条目,它们将包含已填充的标识符

    return result;
}
英文:

Capture the entries before the SaveChanges and process them after - they will contain the updated ids. For example:

public override int SaveChanges()
{
    var entries = GetChangesByType(...);

    var result = base.SaveChanges();

    // process/log the entries, which will have ids filled
    
    return result;
}

huangapple
  • 本文由 发表于 2023年3月3日 21:38:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/75627798.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定