Override SaveChangesAsync Entity Framework 6 to log modified property values - c#

I'm developing an ASP.NET Core project where in SaveChanges, I need to log the updated values
According to this I tried to override SaveChangesAsync but I get this error :
Unable to cast object of type 'MyProject.ApplicationDbContext' to type 'System.Data.Entity.Infrastructure.IObjectContextAdapter'.
Code:
public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
{
ChangeTracker.DetectChanges();
ObjectContext ctx = ((IObjectContextAdapter)this).ObjectContext;
List<ObjectStateEntry> objectStateEntryList = ctx.ObjectStateManager
.GetObjectStateEntries((System.Data.Entity.EntityState)(EntityState.Added | EntityState.Modified | EntityState.Deleted))
.ToList();
foreach (ObjectStateEntry entry in objectStateEntryList)
{
if (!entry.IsRelationship)
{
switch (entry.State)
{
case (System.Data.Entity.EntityState)EntityState.Added:
// write log...
break;
case (System.Data.Entity.EntityState)EntityState.Deleted:
// write log...
break;
case (System.Data.Entity.EntityState)EntityState.Modified:
foreach (string propertyName in entry.GetModifiedProperties())
{
DbDataRecord original = entry.OriginalValues;
string oldValue = original.GetValue(original.GetOrdinal(propertyName)).ToString();
CurrentValueRecord current = entry.CurrentValues;
string newValue = current.GetValue(current.GetOrdinal(propertyName)).ToString();
if (oldValue != newValue) // probably not necessary
{
var a = string.Format("Entry: {0} Original :{1} New: {2}",
entry.Entity.GetType().Name,
oldValue, newValue);
}
}
break;
}
}
}
return base.SaveChangesAsync();
}
Also I tried to compose the log string in the Action method but I get the same error.
public async Task<IActionResult> Edit(MyModel model)
{
...
// _context is ApplicationDbContext()
var myObjectState = _context.ObjectStateManager.GetObjectStateEntry(model);
var modifiedProperties = myObjectState.GetModifiedProperties();
foreach (var propName in modifiedProperties)
{
Console.WriteLine("Property {0} changed from {1} to {2}",
propName,
myObjectState.OriginalValues[propName],
myObjectState.CurrentValues[propName]);
}
}
I'm using EF 6.
I need to log the property name, old value and new value. I can't get why I'm getting that error, what am I doing wrong?

what am I doing wrong?
Using an example from EF 4.1? :)
You can utilize the ChangeTracker in EF 6 to accomplish what you are looking for. I would recommend setting up a separate DbContext for your logging containing just the logging table and FKs as needed:
Within your SaveChanges/SaveChangesAsync overrides:
var updatedEntities = ChangeTracker.Entries()
.Where(x => x.State == EntityState.Modified);
var insertedEntities = ChangeTracker.Entries()
.Where(x => x.State == EntityState.Added);
From here you can access the original and modified property values through OriginalValues and CurrentValues respectively.
** Update **
When reporting on changes the typical easy way is to use ToObject() on the OriginalValues and CurrentValues then serialize to something like Json to capture the before and after state of the object in question. However this will display all modified and unmodified values.
To iterate through the values to find actual changes is a bit more involved:
foreach(var entity in updatedEntities)
{
foreach (var propertyName in entity.OriginalValues.PropertyNames)
{
if (!object.Equals(entity.OriginalValues.GetValue<object>(propertyName),
entity.CurrentValues.GetValue<object>(propertyName)))
{
var columnName = propertyName;
var originalValue = entity.OriginalValues.GetValue<object>(propertyName)?.ToString() ?? "#null";
var updatedValue = entity.CurrentValues.GetValue<object>(propertyName)?.ToString() ?? "#null";
var message = $"The prop: {columnName} has been changed from {originalValue} to {updatedValue}";
}
}
}

Related

Replace property values in a class from List<Dictionary> values

I have a method that takes a List<Dictionary<string,object>> as a parameter. The plan is to use that parameter, but only update the values held in a particular class. Here is the (partially written) method
public async Task<Errors> UpdatePageForProject(Guid projectId, List<Dictionary<string, object>> data)
{
if (!IsValidUserIdForProject(projectId))
return new Errors { ErrorMessage = "Project does not exist", Success = false };
if (data.Count == 0)
return new Errors { ErrorMessage = "No data passed to change", Success = false };
var page = await _context.FlowPages.FirstOrDefaultAsync(t => t.ProjectId == projectId);
foreach (var d in data)
{
}
return new Errors { Success = true };
}
My original plan is to take each dictionary, check if the key and the property in page match and then alter the value (so I can pass in 1 dictionary or 8 dictionaries in the list and then alter page to save back to my entity database).
I'd rather not use reflection due to the speed hit (though C#9 is really fast, I'd still rather not use it), but I'm not sure how else this can be done. I did consider using AutoMapper to do this, but for now would rather not (it's a PoC, so it is possibly overkill)
If you want to do this without Reflection (which I agree is a good idea, not just for performance reasons) then you could use a "map" or lookup table with actions for each property.
var map = new Dictionary<string,Action<Page,object>>()
{
{ "Title", (p,o) => p.Title = (string)o },
{ "Header", (p,o) => p.Field1 = (string)o },
{ "DOB", (p,o) => p.DateOfBirth = (DateTime)o }
};
You can then iterate over your list of dictionaries and use the map to execute actions that update the page.
foreach (var dictionary in data)
{
foreach (entry in dictionary)
{
var action = map[entry.Key];
action(page, entry.Value);
}
}

Unique Indexes convention in EF6

How to create custom index and key conventions for different type of indexes. I need different naming for following key or index types:
PK_TableName Primary keys
FK_SourceTable_Column_TargetTable for foreign keys
IX_TableName_Column1_Column2 Non-unique indexes
UX_TableName_Column1_Column2 Unique indexes
By defaults, Entity Framework uses following namings:
PK_schemaname.TableName for primary keys
FK_schemaname.SourceTable_schemaname.TargetTable_Column1 for foreign keys
IX_Column1 for non-unique indexes
ColumnName for unique indexes
I've found out that I can implement IStoreModelConvention<T>, but I haven't found particular type to use as type parameter.
Moreover, there're can be Custom Code-First Conventions, but my research is ended with no results. How I can get mentioned naming rules when I use Entity Framework Code First? It can be anything: package, sample, or just direction for following researches.
Mission impossible for PK and FK. The problems is that there is no special EdmModel property/attribute/annotation for naming the store constraint - in the model they are basically represented as list of columns (properties) and the naming convention is hardcoded inside the migration builder classes. Please note that some examples mentioned in the comments are showing how to rename the FK columns (properties), not the FK constraint itself.
Luckily for indexes, although not simple, but it's possible, thanks to the IndexAttribute and IndexAnnotation. This is because the annotation (with attribute) is associated with column (entity property), and then consolidated by an internal class called ConsolidatedIndex.
So in order to achieve the goal, you have to create IStoreModelConvention<EntityType>, prepare a consolidated index info from properties similar to how ConsolidatedIndex class does it, determine the new name based on your rules for the unnamed indexes or indexes with default name generated for FK constrains by the ForeignKeyIndexConvention, and update the corresponding IndexAnnotation of the properties.
With that being said, here is the code for applying your index name convention:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Core.Metadata.Edm;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Infrastructure.Annotations;
using System.Data.Entity.Migrations.Model;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Linq;
public class IndexNameConvention : IStoreModelConvention<EntityType>
{
public void Apply(EntityType item, DbModel model)
{
// Build index info, consolidating indexes with the same name
var indexInfo = new List<IndexInfo>();
foreach (var p in item.Properties)
{
foreach (var mp in p.MetadataProperties)
{
var a = mp.Value as IndexAnnotation;
if (a == null) continue;
foreach (var index in a.Indexes)
{
var info = index.Name != null ? indexInfo.FirstOrDefault(e => e.Name == index.Name) : null;
if (info == null)
{
info = new IndexInfo { Name = index.Name };
indexInfo.Add(info);
}
else
{
var other = info.Entries[0].Index;
if (index.IsUnique != other.IsUnique || index.IsClustered != other.IsClustered)
throw new Exception("Invalid index configuration.");
}
info.Entries.Add(new IndexEntry { Column = p, Annotation = mp, Index = index });
}
}
}
if (indexInfo.Count == 0) return;
// Generate new name where needed
var entitySet = model.StoreModel.Container.EntitySets.First(es => es.ElementType == item);
foreach (var info in indexInfo)
{
var columns = info.Entries.OrderBy(e => e.Index.Order).Select(e => e.Column.Name);
if (info.Name == null || info.Name == IndexOperation.BuildDefaultName(columns))
{
bool unique = info.Entries[0].Index.IsUnique;
var name = string.Format("{0}_{1}_{2}", unique ? "UX" : "IX", entitySet.Table, string.Join("_", columns));
if (name.Length > 128) name = name.Substring(0, 128);
if (info.Name == name) continue;
foreach (var entry in info.Entries)
{
var index = new IndexAttribute(name);
if (entry.Index.Order >= 0)
index.Order = entry.Index.Order;
if (entry.Index.IsUniqueConfigured)
index.IsUnique = entry.Index.IsUnique;
if (entry.Index.IsClusteredConfigured)
index.IsClustered = entry.Index.IsClustered;
entry.Index = index;
entry.Modified = true;
}
}
}
// Apply the changes
foreach (var g in indexInfo.SelectMany(e => e.Entries).GroupBy(e => e.Annotation))
{
if (g.Any(e => e.Modified))
g.Key.Value = new IndexAnnotation(g.Select(e => e.Index));
}
}
class IndexInfo
{
public string Name;
public List<IndexEntry> Entries = new List<IndexEntry>();
}
class IndexEntry
{
public EdmProperty Column;
public MetadataProperty Annotation;
public IndexAttribute Index;
public bool Modified;
}
}
All you need is to add it to the DbModelBuilder.Conventions in your OnModelCreating:
modelBuilder.Conventions.Add<IndexNameConvention>();

Code first track database changes [duplicate]

Is there a way to get all the changes made to a object in the Entity Framework before it saves all changes. The reason for this is that i want to create a log table in our clients database:
so...
Is there a way to get the current database values(old) and the new values(current) before changes are saved?
If not, how can i achieve this in a generic way, so all my View Models can inherit from this?(I am using the MVVM + M Structure)
You can use ObjectContext's ObjectStateManager,GetObjectStateEntry to get an object's ObjectStateEntry, which holds its original and current values in the OriginalValues and CurrentValues properties. You can get the names of the properties that changed using the GetModifiedProperties method.
You can write something like:
var myObjectState=myContext.ObjectStateManager.GetObjectStateEntry(myObject);
var modifiedProperties=myObjectState.GetModifiedProperties();
foreach(var propName in modifiedProperties)
{
Console.WriteLine("Property {0} changed from {1} to {2}",
propName,
myObjectState.OriginalValues[propName],
myObjectState.CurrentValues[propName]);
}
For EF5 upwards you can log your changes in the SaveChanges() method like this:
public override int SaveChanges()
{
var changes = from e in this.ChangeTracker.Entries()
where e.State != System.Data.EntityState.Unchanged
select e;
foreach (var change in changes)
{
if (change.State == System.Data.EntityState.Added)
{
// Log Added
}
else if (change.State == System.Data.EntityState.Modified)
{
// Log Modified
var item = change.Cast<IEntity>().Entity;
var originalValues = this.Entry(item).OriginalValues;
var currentValues = this.Entry(item).CurrentValues;
foreach (string propertyName in originalValues.PropertyNames)
{
var original = originalValues[propertyName];
var current = currentValues[propertyName];
if (!Equals(original, current))
{
// log propertyName: original --> current
}
}
}
else if (change.State == System.Data.EntityState.Deleted)
{
// log deleted
}
}
// don't forget to save
base.SaveChanges();
}
I use this extension function that provides details on the entity being changed, the old and new values, the datatype, and the entity key.
This is tested with EF 6.1 using ObjectContext and uses log4net for output.
/// <summary>
/// dump changes in the context to the debug log
/// <para>Debug logging must be turned on using log4net</para>
/// </summary>
/// <param name="context">The context to dump the changes for</param>
public static void DumpChanges(this ObjectContext context)
{
context.DetectChanges();
// Output any added entries
foreach (var added in context.ObjectStateManager.GetObjectStateEntries(EntityState.Added))
{
Log.DebugFormat("{0}:{1} {2} {3}",
added.State,
added.Entity.GetType().FullName,
added.Entity.ToString(),
string.Join(",",
added.CurrentValues.GetValue(1),
added.CurrentValues.GetValue(2))
);
}
foreach (var modified in context.ObjectStateManager.GetObjectStateEntries(EntityState.Modified))
{
// Put original field values into dictionary
var originalValues = new Dictionary<string,int>();
for (var i = 0; i < modified.OriginalValues.FieldCount; ++i)
{
originalValues.Add(modified.OriginalValues.GetName(i), i);
}
// Output each of the changed properties.
foreach (var entry in modified.GetModifiedProperties())
{
var originalIdx = originalValues[entry];
Log.DebugFormat("{6} = {0}.{4} [{7}][{2}] [{1}] --> [{3}] Rel:{5}",
modified.Entity.GetType(),
modified.OriginalValues.GetValue(originalIdx),
modified.OriginalValues.GetFieldType(originalIdx),
modified.CurrentValues.GetValue(originalIdx),
modified.OriginalValues.GetName(originalIdx),
modified.IsRelationship,
modified.State,
string.Join(",",
modified.EntityKey.EntityKeyValues
.Select(v => string.Join(" = ", v.Key, v.Value))
)
);
}
}
// Output any deleted entries
foreach (var deleted in context.ObjectStateManager.GetObjectStateEntries(EntityState.Deleted))
{
Log.DebugFormat("{1} {0} {2}",
deleted.Entity.GetType().FullName,
deleted.State,
string.Join(",",
deleted.CurrentValues.GetValue(1),
deleted.CurrentValues.GetValue(2))
);
}
}
Use the IsModified field of each property, which is accessible by Context.Entry(Entity).Properties.
In this example, the modified entries are listed as a Tuple of the original and current values, indexed by name. Use any conversion that is required to build the audit log.
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
//...
// gets somewhere in the scope
DbContext Context;
// Some entity that has been modified, but not saved and is being tracked by Context
object Entity;
//...
Dictionary<string, System.Tuple<object, object>> modified =
Context.Entry(Entity)
.Properties.Where(p => p.IsModified)
.ToDictionary(p => p.Metadata.Name,
p => new System.Tuple<object,object>(p.OriginalValue, p.CurrentValue));
//...
Uses Entity Framework Core 3.1. Try it for EF 6.4, but it may not work.

how to could use reflection to write to the appropriate properties on the entity?

How to: you don't want to manually write code to write to ColumnA, ColumnB, etc, then you could use reflection to write to the appropriate properties on the entity?
you can create a new instance of this class and its property values. These property values are mapped to columns in the SQL database table. You then pass this object to the DataContext class generated by LINQ to SQL, to add a new row to the table in the database.
So, you would do something like this:
For a database table with columns "ColumnA", "ColumnB" and "ColumnC"
var myEntity = new EntityObject { ColumnA = "valueA", ColumnB = "valueB", "ColumnC" = "valueC" };
DataContext.InsertOnSubmit(myEntity);
DataContext.SubmitChanges();
This will insert a new row into the database with the column values specified.
Now if you don't want to manually write code to write to ColumnA, ColumnB, etc, then you could use reflection to write to the appropriate properties on the entity:
For example, with entity instance 'myEntity':
var properties = myEntity.GetType().GetProperties();
foreach (string ky in ld.Keys)
{
var matchingProperty = properties.Where(p => p.Name.Equals(ky)).FirstOrDefault();
if (matchingProperty != null)
{
matchingProperty.SetValue(myEntity, ld[ky], null);
}
}
i try to this but i cannot. How can you make it?
Check this article : LINQ to SQL: All common operations (Insert, Update, Delete, Get) in one base class
Following might help you :
protected virtual void Update(T entity, Expression<Func<T, bool>> query)
{
using (DC db = new DC())
{
object propertyValue = null;
T entityFromDB = db.GetTable<T>().Where(query).SingleOrDefault();
if (null == entityFromDB)
throw new NullReferenceException("Query Supplied to " +
"Get entity from DB is invalid, NULL value returned");
PropertyInfo[] properties = entityFromDB.GetType().GetProperties();
foreach (PropertyInfo property in properties)
{
propertyValue = null;
if (null != property.GetSetMethod())
{
PropertyInfo entityProperty =
entity.GetType().GetProperty(property.Name);
if (entityProperty.PropertyType.BaseType ==
Type.GetType("System.ValueType")||
entityProperty.PropertyType ==
Type.GetType("System.String"))
propertyValue =
entity.GetType().GetProperty(property.Name).GetValue(entity, null);
if (null != propertyValue)
property.SetValue(entityFromDB, propertyValue, null);
}
}
db.SubmitChanges();
}
}

Getting all changes made to an object in the Entity Framework

Is there a way to get all the changes made to a object in the Entity Framework before it saves all changes. The reason for this is that i want to create a log table in our clients database:
so...
Is there a way to get the current database values(old) and the new values(current) before changes are saved?
If not, how can i achieve this in a generic way, so all my View Models can inherit from this?(I am using the MVVM + M Structure)
You can use ObjectContext's ObjectStateManager,GetObjectStateEntry to get an object's ObjectStateEntry, which holds its original and current values in the OriginalValues and CurrentValues properties. You can get the names of the properties that changed using the GetModifiedProperties method.
You can write something like:
var myObjectState=myContext.ObjectStateManager.GetObjectStateEntry(myObject);
var modifiedProperties=myObjectState.GetModifiedProperties();
foreach(var propName in modifiedProperties)
{
Console.WriteLine("Property {0} changed from {1} to {2}",
propName,
myObjectState.OriginalValues[propName],
myObjectState.CurrentValues[propName]);
}
For EF5 upwards you can log your changes in the SaveChanges() method like this:
public override int SaveChanges()
{
var changes = from e in this.ChangeTracker.Entries()
where e.State != System.Data.EntityState.Unchanged
select e;
foreach (var change in changes)
{
if (change.State == System.Data.EntityState.Added)
{
// Log Added
}
else if (change.State == System.Data.EntityState.Modified)
{
// Log Modified
var item = change.Cast<IEntity>().Entity;
var originalValues = this.Entry(item).OriginalValues;
var currentValues = this.Entry(item).CurrentValues;
foreach (string propertyName in originalValues.PropertyNames)
{
var original = originalValues[propertyName];
var current = currentValues[propertyName];
if (!Equals(original, current))
{
// log propertyName: original --> current
}
}
}
else if (change.State == System.Data.EntityState.Deleted)
{
// log deleted
}
}
// don't forget to save
base.SaveChanges();
}
I use this extension function that provides details on the entity being changed, the old and new values, the datatype, and the entity key.
This is tested with EF 6.1 using ObjectContext and uses log4net for output.
/// <summary>
/// dump changes in the context to the debug log
/// <para>Debug logging must be turned on using log4net</para>
/// </summary>
/// <param name="context">The context to dump the changes for</param>
public static void DumpChanges(this ObjectContext context)
{
context.DetectChanges();
// Output any added entries
foreach (var added in context.ObjectStateManager.GetObjectStateEntries(EntityState.Added))
{
Log.DebugFormat("{0}:{1} {2} {3}",
added.State,
added.Entity.GetType().FullName,
added.Entity.ToString(),
string.Join(",",
added.CurrentValues.GetValue(1),
added.CurrentValues.GetValue(2))
);
}
foreach (var modified in context.ObjectStateManager.GetObjectStateEntries(EntityState.Modified))
{
// Put original field values into dictionary
var originalValues = new Dictionary<string,int>();
for (var i = 0; i < modified.OriginalValues.FieldCount; ++i)
{
originalValues.Add(modified.OriginalValues.GetName(i), i);
}
// Output each of the changed properties.
foreach (var entry in modified.GetModifiedProperties())
{
var originalIdx = originalValues[entry];
Log.DebugFormat("{6} = {0}.{4} [{7}][{2}] [{1}] --> [{3}] Rel:{5}",
modified.Entity.GetType(),
modified.OriginalValues.GetValue(originalIdx),
modified.OriginalValues.GetFieldType(originalIdx),
modified.CurrentValues.GetValue(originalIdx),
modified.OriginalValues.GetName(originalIdx),
modified.IsRelationship,
modified.State,
string.Join(",",
modified.EntityKey.EntityKeyValues
.Select(v => string.Join(" = ", v.Key, v.Value))
)
);
}
}
// Output any deleted entries
foreach (var deleted in context.ObjectStateManager.GetObjectStateEntries(EntityState.Deleted))
{
Log.DebugFormat("{1} {0} {2}",
deleted.Entity.GetType().FullName,
deleted.State,
string.Join(",",
deleted.CurrentValues.GetValue(1),
deleted.CurrentValues.GetValue(2))
);
}
}
Use the IsModified field of each property, which is accessible by Context.Entry(Entity).Properties.
In this example, the modified entries are listed as a Tuple of the original and current values, indexed by name. Use any conversion that is required to build the audit log.
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
//...
// gets somewhere in the scope
DbContext Context;
// Some entity that has been modified, but not saved and is being tracked by Context
object Entity;
//...
Dictionary<string, System.Tuple<object, object>> modified =
Context.Entry(Entity)
.Properties.Where(p => p.IsModified)
.ToDictionary(p => p.Metadata.Name,
p => new System.Tuple<object,object>(p.OriginalValue, p.CurrentValue));
//...
Uses Entity Framework Core 3.1. Try it for EF 6.4, but it may not work.

Categories