Skip to content

Instantly share code, notes, and snippets.

@afruzan
Last active December 31, 2020 14:12
Show Gist options
  • Save afruzan/dbb57982162f17ab0aea252404cfa879 to your computer and use it in GitHub Desktop.
Save afruzan/dbb57982162f17ab0aea252404cfa879 to your computer and use it in GitHub Desktop.
// ef core 5
// after add/modify/delete some entities at a sync api, i recommend logging changes deeply.
// also it is best practice that returning the `changes` to client throw responce both in seccess and fail situation.
private object logContextChanges()
{
var changes = _context.ChangeTracker.Entries()
.Where(i => i.State != EntityState.Unchanged).Select(t => new
{
state = t.State.ToString(),
type = t.Entity.GetType().FullName,
props =
t.State == EntityState.Added ?
t.Properties.Select(p => new
{
propName = p.Metadata.Name,
propType = p.Metadata.ClrType.FullName,
oldValue = (object)null,
newValue = p.CurrentValue,
modified = (bool?)null,
changed = (bool?)null,
}) :
t.State == EntityState.Modified ?
t.Properties.Select(p => new
{
propName = p.Metadata.Name,
propType = p.Metadata.ClrType.FullName,
oldValue = p.OriginalValue,
newValue = p.CurrentValue,
modified = (bool?)p.IsModified,
changed = (bool?)!(p.CurrentValue == p.OriginalValue || p.CurrentValue.Equals(p.OriginalValue)),
}) :
t.Properties.Select(p => new
{
propName = p.Metadata.Name,
propType = p.Metadata.ClrType.FullName,
oldValue = p.CurrentValue,
newValue = (object)null,
modified = (bool?)null,
changed = (bool?)null,
}),
}).ToArray();
return new
{
changesCount = changes.GroupBy(i => new { i.type, i.state }).Select(i => new
{
i.Key.state,
i.Key.type,
count = i.Count(),
changedCount = i.Where(j => j.props.Any(k => k.changed != false)).Count(),
}).ToArray(),
changes = changes
};
var changesText = System.Text.Json.JsonSerializer.Serialize(changes, new System.Text.Json.JsonSerializerOptions(System.Text.Json.JsonSerializerDefaults.Web) { WriteIndented = true });
_logger.LogInformation($"Sync site info... changes = {changesText}");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment