In my code I am tracking change in my object by comparing current and old values using reflection over properties. I have one field of type decimal(5,2)
in the database.
So when I pass, say 12
to the database from front end it gets stored as 12.00
, this is fine. But if I try to save the object again with the value 12 the update tracker finds it different than the current value, so update tracker says
12 != 12.00
And so it records it as an update which actually is not because they are same values.
How can I check for the equivalence of such values?
EDIT
From update tracker I mean that I have written my own method SaveChanges
in TemplateContext of EntityFramework which when called actually call the native SaveChanges
method but before that it iterates through all the properties of the object using Reflection and tracks the change in the property and if there is a change then inserts in into one of my database tables to show the logs to the user of what all is changes and when.
So in that code I am checking the old value that is stored in the database and the new value that is provided by the UI.
So that property in my C# class is of type decimal and so I am not actually comparing int with decimal, I am checking decimal value with a decimal value.
So 12
is also stored in a decimal
property and 12.00
is also stored in a decimal
property
Edit 2
This is method that is tracking the change
public int SaveChanges(string personnelNo, string fullName, DateTime? now = null)
{
var modifiedEntities = ChangeTracker.Entries().Where(p => p.State == EntityState.Modified).ToList();
now = now ?? DateTime.UtcNow;
foreach (var change in modifiedEntities)
{
var entityName = change.Entity.GetType().Name;
var primaryKey = GetPrimaryKeyValue(change);
foreach (var prop in change.OriginalValues.PropertyNames.Where(p=> skipUpdatesProperties.Any(s=> s==p) == false))
{
// below are the two lines which get original and current value
// originalValue is coming from the database as 12.00
// currentValue is coming from UI as 12
// This is where it fails and says that the values are different
// I also tried removing ToString() also and comparing directly that also doesn't work
var originalValue = change.OriginalValues[prop]?.ToString();
var currentValue = change.CurrentValues[prop]?.ToString();
if (originalValue != currentValue) //Only create a log if the value changes
{
//Create the Change Log
var ut = new Model.UpdateTracker
{
Id = Guid.NewGuid(),
TableName = entityName,
TableKey = primaryKey.ToString(),
FieldName = prop,
OldValue = originalValue,
NewValue = currentValue,
CreatedOn = now.Value,
CreatedBy = personnelNo,
CreatedByFullName = fullName
};
this.UpdateTrackers.Add(ut);
this.Entry(ut).State = EntityState.Added;
}
}
}
return base.SaveChanges();
}