.NET Tips and Tricks

Blog archive

Check to See What's Changed in Entity Framework

When you call Entity Framework's SaveChanges method, Entity Framework has to know what entities have changed in order to figure out what SQL Update/Delete/Insert statements to generate. If you also want to find out what entities have changed, then you can access that information through the DbContext object's ChangeTracker property.

The ChangeTracker property holds Entity Framework's DbChangeTracker object, which, in turn, has a collection called Entries that holds all objects being tracked. This code, for example, writes to some kind of log the name of the classes with pending changes, along with their current state (for example, Modified, Added, Deleted and so on):

CustomerEntities db = new CustomerEntities();
// ... make changes to objects in db ... 

//Record pending changes
foreach (DbEntityEntry e in db.ChangeTracker.Entries())
{
  AuditLog.Write("Name and Status: {0} is {1}", e.Entity.GetType().FullName, e.State);
}

If you want to get the primary key value for the objects being changed, this code will build a string out of all the values for the properties that make up the primary key:

IObjectContextAdapter oca = (IObjectContextAdapter) db;
ObjectStateManager osm = oca.ObjectContext.ObjectStateManager;
ObjectStateEntry ose = osm.GetObjectStateEntry(e.Entity);

string keys;
keys = string.Empty;
foreach(object key in ose.EntityKey.EntityKeyValues)
{
  keys = keys + key.ToString() + "/";
}

I've assumed in this code that it's very unusual to have an entity whose primary key consists of multiple properties. If that's not true for you, then you should probably use the StringBuilder class to hold your concatenated key values rather than a simple string.

If you do go that extra mile, you could incorporate that information into your log entry. It might also make sense to write to your log as comma-delimited values so you can load the log into Excel for analysis. That code would look like this:

AuditLog.Write("{0},{1},{2}", e.Entity.GetType().FullName, keys, e.State);

Posted by Peter Vogel on 11/27/2018


comments powered by Disqus

Featured

  • Diving Deep into .NET MAUI

    Ever since someone figured out that fiddling bits results in source code, developers have sought one codebase for all types of apps on all platforms, with Microsoft's latest attempt to further that effort being .NET MAUI.

  • Copilot AI Boosts Abound in New VS Code v1.96

    Microsoft improved on its new "Copilot Edit" functionality in the latest release of Visual Studio Code, v1.96, its open-source based code editor that has become the most popular in the world according to many surveys.

  • AdaBoost Regression Using C#

    Dr. James McCaffrey from Microsoft Research presents a complete end-to-end demonstration of the AdaBoost.R2 algorithm for regression problems (where the goal is to predict a single numeric value). The implementation follows the original source research paper closely, so you can use it as a guide for customization for specific scenarios.

  • Versioning and Documenting ASP.NET Core Services

    Building an API with ASP.NET Core is only half the job. If your API is going to live more than one release cycle, you're going to need to version it. If you have other people building clients for it, you're going to need to document it.

  • TypeScript Tops New JetBrains 'Language Promise Index'

    In its latest annual developer ecosystem report, JetBrains introduced a new "Language Promise Index" topped by Microsoft's TypeScript programming language.

Subscribe on YouTube