我有一个继承自 DbContext 并覆盖 SaveChanges 方法的类。在这个新的 SaveChanges 方法中,我将一条记录插入到审计表中。
可以被审计的实体:
public class Fruit
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long FruitId{ get; set; }
public string FruitName{ get; set; }
}
FruitAudit 表的模型:
public class FruitAudit
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long FruitAuditId{ get; set; }
public long FruitId{ get; set; }
// Auditing properties like modifying user and timestamps.
}
还有我重写的 SaveChanges 方法:
public int SaveChanges()
{
var entriesToAudit = this.ChangeTracker.Entries().Where(p =>
(p.State == System.Data.EntityState.Added || p.State == System.Data.EntityState.Deleted || p.State == System.Data.EntityState.Modified);
foreach (var entity in entriesToAudit)
{
using (var context = new StoreContext())
{
Fruit fruit = entity.Entity as Fruit;
FruitAudit audit = new FruitAudit()
{
FruitId = Fruit.FruitId;
// Other auditing properties set here
}
context.FruitAudits.Add(audit);
context.SaveChanges();
}
}
return base.SaveChanges();
}
插入 Fruit 时发生错误,因为在尝试保存 FruitAudit 记录时尚未设置 FruitId。FruitId 是从数据库自动生成的,但实际的 Fruit 对象在插入审计记录之后才会保存。如何将此 FruitAudit 与插入的 Fruit 关联?