Skip to content

Instantly share code, notes, and snippets.

@ssippe
Created December 23, 2022 03:57
Show Gist options
  • Save ssippe/b0af62d50eaa44e9d37fe57271db26c8 to your computer and use it in GitHub Desktop.
Save ssippe/b0af62d50eaa44e9d37fe57271db26c8 to your computer and use it in GitHub Desktop.
using System.Linq;
using System.Data.Entity.Infrastructure;
using System;
namespace Reckon.Data.EF
{
public static class DbChangeTrackerExtension
{
/// <summary>
/// Get a summary of Tracked Changes on a DbContext.ChangeTracker
/// </summary>
/// <param name="dbChangeTracker">DbContext.ChangeTracker</param>
/// <example>
/// Debug.WriteLine(myDbContext.ChangeTracker.GetTrackedChangesSummary());
/// </example>
public static string GetTrackedChangesSummary(this DbChangeTracker dbChangeTracker)
{
var linesByEntityState = string.Join(Environment.NewLine, dbChangeTracker.Entries()
.GroupBy(f => new { entityName = f.Entity.GetType().Name, f.State })
.OrderBy(f => f.Key.entityName).ThenBy(f => f.Key.State)
.Select(f => $"entity={f.Key.entityName}, state={f.Key.State}, count={f.Count()}"));
var byState = string.Join(", ", dbChangeTracker.Entries()
.GroupBy(f => f.State)
.OrderBy(f => f.Key)
.Select(f => $"{f.Key}={f.Count()}"));
var totals = $"TOTALS total={dbChangeTracker.Entries().Count()}, {byState}";
return string.Join(Environment.NewLine, new[] { linesByEntityState, totals });
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment