EntityFramework更改跟踪不跟踪更改

asp.net-core c# entity-framework entity-framework-core

我正在使用Entity Framework 7,我需要能夠跟踪更改。我最終在SaveChanges上做了類似的事情我在覆蓋它然後在最後使用base.SaveChanges():

foreach (var ent in this.ChangeTracker.Entries().Where(p => p.State == EntityState.Deleted || p.State == EntityState.Modified).ToList())
{
    // For each changed record, get the audit record entries and add them
    foreach (TableChange x in GetTableChangeRecordsForChange(ent, _ChangeUser))
    {
        this.TableChanges.Add(x);
        val = true;
    }
}

這最終要求獲取表更改記錄:

foreach (var ent in this.ChangeTracker.Entries().Where(p => p.State == EntityState.Deleted || p.State == EntityState.Modified).ToList())
{
    // For each changed record, get the audit record entries and add them
    foreach (TableChange x in GetTableChangeRecordsForChange(ent, _ChangeUser))
    {
        this.TableChanges.Add(x);
        val = true;
    }
}

現在我面臨的問題是OriginalValue和CurrentValue以及輸入的新值。它不跟踪原始值是什麼。

我有:

foreach (var ent in this.ChangeTracker.Entries().Where(p => p.State == EntityState.Deleted || p.State == EntityState.Modified).ToList())
{
    // For each changed record, get the audit record entries and add them
    foreach (TableChange x in GetTableChangeRecordsForChange(ent, _ChangeUser))
    {
        this.TableChanges.Add(x);
        val = true;
    }
}

然而,我仍然無法正確地向我提供原始和當前價值。任何幫助是極大的讚賞。

一般承認的答案

所以我想出了自己的問題......我面臨的問題是我附加了需要更新的記錄。我最終通過創建更新功能更新了記錄:

public T ADMSUpdate<T>(T entity, T originalEntity)
    {
        object propertyValue = null;
        PropertyInfo[] properties = originalEntity.GetType().GetProperties();
        foreach (PropertyInfo property in properties)
        {
            propertyValue = null;
            if (null != property.GetSetMethod())
            {
                PropertyInfo entityProperty = entity.GetType().GetProperty(property.Name);
                propertyValue = entity.GetType().GetProperty(property.Name).GetValue(entity, null);

                if (null != propertyValue)
                {
                    property.SetValue(originalEntity, propertyValue, null);
                }
            }
        }
        return entity;
    }



許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因