Reputation: 20997
I'm trying to create a custom When Extensions to check if my entity has changes. But I'm having trouble getting the Propertyname, which I need with the instance being validated.
public static bool WhenHasChanged<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule)
{
//I need to get the PropertyValidatorContext from the rule
PropertyValidatorContext context;
var instance = (IChangeTrackingObject)context.Instance;
if (false == instance.GetChangedProperties().ContainsKey(context.PropertyName))
{
return true;
}
var oldValue = instance.GetChangedProperties().Get(context.PropertyName).OldValue;
var newValue = context.PropertyValue;
return (null == oldValue) ? null == newValue : oldValue.Equals(newValue);
}
I need to get the PropertyName being validated and the instance that's being validated, normally these lie within the PropertyValidatorContext
is there a way to get the PropertyValidatorContext
from the rule?
Upvotes: 1
Views: 1234
Reputation: 20997
I ended up creating a must extensions in stead so I had access to the property validator context:
private static Func<T, TProperty, PropertyValidatorContext, bool> MustWhenChangedPredicate<T, TProperty>(Func<T, TProperty, PropertyValidatorContext, bool> predicate)
{
return (t, p, context) =>
{
var instance = (IChangeTrackingObject)context.Instance;
//The type name always prefixes the property
var propertyName = context.PropertyName.Split(new[] { '.' }, 2).Skip(1).First();
if (false == instance.GetChangedProperties().ContainsKey(propertyName))
{
return true;
}
var oldValue = instance.GetChangedProperties().Get(propertyName).OldValue;
var newValue = context.PropertyValue;
if (oldValue == null && newValue == null)
{
return true;
}
if ((oldValue != null && oldValue.Equals(newValue)) ||
(newValue != null && newValue.Equals(oldValue)))
{
return true;
}
return predicate(t, p, context);
};
}
Upvotes: 1