【发布时间】:2021-05-23 14:15:37
【问题描述】:
我正在开发一个 ASP.NET Core 项目,在 SaveChanges 中,我需要记录更新后的值
根据this,我尝试覆盖SaveChangesAsync,但出现此错误:
无法将“MyProject.ApplicationDbContext”类型的对象转换为“System.Data.Entity.Infrastructure.IObjectContextAdapter”类型。
代码:
public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
{
ChangeTracker.DetectChanges();
ObjectContext ctx = ((IObjectContextAdapter)this).ObjectContext;
List<ObjectStateEntry> objectStateEntryList = ctx.ObjectStateManager
.GetObjectStateEntries((System.Data.Entity.EntityState)(EntityState.Added | EntityState.Modified | EntityState.Deleted))
.ToList();
foreach (ObjectStateEntry entry in objectStateEntryList)
{
if (!entry.IsRelationship)
{
switch (entry.State)
{
case (System.Data.Entity.EntityState)EntityState.Added:
// write log...
break;
case (System.Data.Entity.EntityState)EntityState.Deleted:
// write log...
break;
case (System.Data.Entity.EntityState)EntityState.Modified:
foreach (string propertyName in entry.GetModifiedProperties())
{
DbDataRecord original = entry.OriginalValues;
string oldValue = original.GetValue(original.GetOrdinal(propertyName)).ToString();
CurrentValueRecord current = entry.CurrentValues;
string newValue = current.GetValue(current.GetOrdinal(propertyName)).ToString();
if (oldValue != newValue) // probably not necessary
{
var a = string.Format("Entry: {0} Original :{1} New: {2}",
entry.Entity.GetType().Name,
oldValue, newValue);
}
}
break;
}
}
}
return base.SaveChangesAsync();
}
我也尝试在 Action 方法中编写日志字符串,但我得到了同样的错误。
public async Task<IActionResult> Edit(MyModel model)
{
...
// _context is ApplicationDbContext()
var myObjectState = _context.ObjectStateManager.GetObjectStateEntry(model);
var modifiedProperties = myObjectState.GetModifiedProperties();
foreach (var propName in modifiedProperties)
{
Console.WriteLine("Property {0} changed from {1} to {2}",
propName,
myObjectState.OriginalValues[propName],
myObjectState.CurrentValues[propName]);
}
}
我正在使用 EF 6。
我需要记录属性名称、旧值和新值。我不明白为什么会出现这个错误,我做错了什么?
【问题讨论】:
标签: c# asp.net-mvc entity-framework entity-framework-6