我想要获取实体中发生的更改以及附加到它的相关数据。
我知道如何获取一个实体中已更改的属性名称:
dbContext.Entry(entity).Properties.Where(x => x.IsModified).Select(x => x.Metadata.Name).ToList();
如何对导航属性中的相关数据执行相同的操作?
基于此文章(在实体框架 6 中使用 DbContext 进行实体更改跟踪) https://exceptionnotfound.net/entity-change-tracking-using-dbcontext-in-entity-framework-6/,你应该覆盖SaveChanges()
跟踪实体更改及其相关实体的方法。
public override int SaveChanges()
{
return base.SaveChanges();
}
实际上,您应该将上面的代码更改为以下示例:
public override int SaveChanges()
{
var modifiedEntities = ChangeTracker.Entries()
.Where(p => p.State == EntityState.Modified).ToList();
var now = DateTime.UtcNow;
foreach (var change in modifiedEntities)
{
var entityName = change.Entity.GetType().Name;
var primaryKey = GetPrimaryKeyValue(change);
foreach(var prop in change.OriginalValues.PropertyNames)
{
var originalValue = change.OriginalValues[prop].ToString();
var currentValue = change.CurrentValues[prop].ToString();
if (originalValue != currentValue) //Only create a log if the value changes
{
//Create the Change Log
}
}
}
return base.SaveChanges();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)