Comparing to booleans gives false when they have the same value
Comparing to booleans gives false when they have the same value
I'm trying to implement an audit table using Entity Framework core 2.0. However, all the fields are being saved, not just the edited ones. I thought I could do a simple if statement. If the old value is not equal to the new value then it is a changed value.
However, this is not working for booleans. Two true booleans are coming out as not equal.
Here is my very simple code:
if (property.OriginalValue != property.CurrentValue)
{
auditEntry.OldValues[propertyName] = property.OriginalValue;
auditEntry.NewValues[propertyName] = property.CurrentValue;
}
Hopefully, you can see in the image that both OldValues
and NewValues
are true but it drops into the if
statement when it shouldn't. I would like an if
statement that compares strings, ints, booleans etc if possible.
OldValues
NewValues
if
if
if
What is the value of
property.OriginalValue
? property.OriginalValue.GetType
? property.CurrentValue
? property.CurrentValue.GetType
? Don't guess, please debug and check.– mjwills
Jul 2 at 4:26
property.OriginalValue
property.OriginalValue.GetType
property.CurrentValue
property.CurrentValue.GetType
@mjwills Guess they are an object with a type of bool (see new image in editted post). That is the cause of my issue.
– Tim Long
Jul 2 at 7:27
2 Answers
2
Has to do with the fact that property.OriginalValue and property.CurrentValue are 2 objects. Since the 2 don't reference the same object they are never equal. Try comparing using .ToString() or something like: property.IsModified
property.IsModified was always true for some reason even if they were not modified which is why i couldn't do it that way.
– Tim Long
Jul 2 at 7:28
Fixed it with this line:
if (((property.OriginalValue != null) ? property.OriginalValue.ToString() : "" ) != ((property.CurrentValue != null) ? property.CurrentValue.ToString() : ""))
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Can you show us in the debugger what the two values are set to at the time of the
if
statement?– Kamdroid
Jul 2 at 3:17