gpt4 book ai didi

c# - ChangeTracker.Entries() CurrentValue 等于 EF7 中的 OriginalValue

转载 作者:行者123 更新时间:2023-11-30 20:20:15 25 4
gpt4 key购买 nike

我在 EF7/asp.Net Core 应用程序中遇到问题。在我的上下文中,我创建了一个保存方法:

    public int Save()
{
ChangeTracker.DetectChanges();
var modifiedEntities = ChangeTracker.Entries()
.Where(p => p.State == EntityState.Modified || p.State == EntityState.Added || p.State == EntityState.Deleted || p.State == EntityState.Modified || p.State == EntityState.Detached).ToList();
var now = DateTime.UtcNow;

foreach (var change in modifiedEntities)
{
var entityName = change.Entity.GetType().Name;
var primaryKeyValue = GetPrimaryKeyValue(change.Entity);
foreach (var prop in change.Entity.GetType().GetTypeInfo().DeclaredProperties)
{
if (!prop.GetGetMethod().IsVirtual)
{
var currentValue = change.Property(prop.Name).CurrentValue;
var originalValue = change.Property(prop.Name).OriginalValue;
if (originalValue.ToString() != currentValue.ToString())
{
var changeLoged = new ChangeLog
{
PropertyName = prop.Name,
EntityName = entityName,
PrimaryKeyValue = primaryKeyValue,
DateChange = now,
OldValue = originalValue.ToString(),
NewValue = currentValue.ToString(),
ChangedBy = "test"
};
ChangeLog.Add(changeLoged);
}
}
}
}
return base.SaveChanges();
}

和方法 GetPrimaryKeyValue:

protected virtual int GetPrimaryKeyValue<T>(T entity)
{
var test = entity;
var test2 = test.GetType();
var keyName = this.Model.FindEntityType(test2).FindPrimaryKey().Properties
.Select(x => x.Name).Single();
var result = (int)entity.GetType().GetProperty(keyName).GetValue(entity, null);
if (result < 0)
return -1;

return result;
}

不幸的是,change.Property(prop.Name).CurrentValue 总是等于 OriginalValue,所以如果originalValue.ToString() != currentValue.ToString()

始终返回 false。

最佳答案

替换:

var originalValue = change.Property(prop.Name).OriginalValue;

到:

var originalValue = change.GetDatabaseValues().GetValue<object>(prop.Name);

关于c# - ChangeTracker.Entries() CurrentValue 等于 EF7 中的 OriginalValue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37210914/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com