Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Track database inserts with specific data

I'm maintaining ASP.NET MVC application, which talks to MS SQL database via Entity Framework.

For some time we are observing cases when entities are updated or inserted into the database with specific field null.

This field may be null, but we strongly suspect, that most of these situations should not happen. I'd like to hook some debug code to log all instances of such attempts.

The problem is that I have no idea, where should I do it.

  • Entity is inserted and updated in a lot of places in code;
  • I might override Insert and Update methods of its DBSet descendent, but I won't catch changes caused indirectly (for instance by retrieving the entity from the database, changing it and calling SaveChanges() ).

Where can I put the code, which will be able to access all write modifications to the database on a specific entity?

like image 967
Spook Avatar asked Jul 09 '26 23:07

Spook


1 Answers

I believe you're looking for the ChangeTracking property of your DbContext.

I use a similar method to build history on entities, by capturing what has been changed/added/deleted.

To do this, you can, within your DbContext, override the SaveChanges() method and then intercept the entries that are changing.

Be sure to call base.SaveChanges(); at the end of your override to actually save any changes.

Here for example, lets say your DbContext is called MyAppDbContext

public partial class MyAppDbContext : DbContext
{
    public override int SaveChanges()
    {
         ChangeTracker.Entries().ToList().ForEach(entry =>
        {

            // entry, here, is DbEntityEntry.
            // it will allow you to see original and new values,
            // such as entry.OriginalValues
            // and entry.CurrentValues
            // You can also find its type
            // entry.Entity.GetType()


            switch (entry.State)
            {
                case EntityState.Detached:
                    break;
                case EntityState.Unchanged:
                    break;
                case EntityState.Added:
                    break;
                case EntityState.Deleted:
                    break;
                case EntityState.Modified:
                    break;
            }
        });

       // call the base.SaveChanges();
       base.SaveChanges();    
    }

}
like image 73
Darren Wainwright Avatar answered Jul 13 '26 15:07

Darren Wainwright



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!