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.
SaveChanges() ).Where can I put the code, which will be able to access all write modifications to the database on a specific entity?
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With