'Intercept saving of entities in Entity Framework Core
Is there a way for EF Core to intercept the pre insertion, pre update, pre delete, post insert, post update and post delete events of an entity?
EF core supports interceptors, but I think it's more focused on logging queries https://www.entityframeworktutorial.net/entityframework6/database-command-interception.aspx
I'm looking for a feature like this https://github.com/khellang/EF.Interception
Solution 1:[1]
You already have a class that extends DbContext
. Override the SaveChanges
methods and you can examine the contents of the ChangeTracker
to handle all your pre- event needs;
private void PreSave()
{
foreach (var entry in ChangeTracker.Entries())
{
switch (entry.State)
{...}
}
}
public override async Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default(CancellationToken))
{
PreSave();
return await base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken);
}
public override int SaveChanges(bool accept) {
PreSave();
return base.SaveChanges(accept);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Jeremy Lakeman |