BLAZORLOVER
BLAZORLOVER

Reputation: 2011

Extract changed entities of a specific type when calling SaveChanges()

DbContext:

public class AppContext : DbContext, IAppContext
{
    public AppContext()
    {
        this.Configuration.LazyLoadingEnabled = false;
    }

    public DbSet<User> Users { get; set; }
    public DbSet<Bar> Bars { get; set; }
}
   

I've implemented in-memory caching such that all Users are loaded into memory. GET requests fetch Users from this in-memory cache.

I'd like to "hook into" the AppContext to detect when a User or multiple Users have been modified when calling SaveChanges(), so I can push those changed entities into the Cache service for cache synchronization.

Ideally, I'd be able to do something like this from within the AppContext:

protected override void OnModelUpdate(SomeContextClass contextThing)
{
     IEnumerable<User> changedUsers = contextThing.ExtractChanges<User>();
     customCache.Sync(changedUsers); // handle updates, inserts, deletes in my custom cache
}

How can this be achieved?

Upvotes: 1

Views: 171

Answers (1)

BLAZORLOVER
BLAZORLOVER

Reputation: 2011

@GertArnold feel free to copy/paste this into an answer that I'll accept if you'd like credit!

    public override int SaveChanges()
    {
        var selectedEntityList = ChangeTracker.Entries()
                                .Where(x => x.Entity is User &&
                                (x.State == EntityState.Added || x.State == EntityState.Modified || x.State == EntityState.Deleted));

        foreach (var entity in selectedEntityList)
        {
            User user = (User)entity.Entity;

            if (entity.State == EntityState.Added)
                UserCache.AddNewUser(user);
            else if (entity.State == EntityState.Modified)
                UserCache.UpdateExistingUser(user);
            else if (entity.State == EntityState.Deleted)
                UserCache.DeleteExistingUser(user);
        }

        return base.SaveChanges();
    }

Upvotes: 1

Related Questions