FluentValidations 从 RuleBuilderOptions 获取属性名

我正在尝试创建一个自定义 When Extensions 来检查我的实体是否有更改。但是我在获取 Propertyname 时遇到了麻烦,这是我在验证实例时需要的。


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);

}

我需要得到正在验证的 PropertyName 和正在验证的实例,通常这些位于PropertyValidatorContext有没有办法PropertyValidatorContext从规则中获取?


HUWWW
浏览 160回答 1
1回答

牧羊人nacy

我最终创建了一个 must 扩展,所以我可以访问属性验证器上下文:private static Func<T, TProperty, PropertyValidatorContext, bool> MustWhenChangedPredicate<T, TProperty>(Func<T, TProperty, PropertyValidatorContext, bool> predicate){&nbsp; &nbsp; return (t, p, context) =>&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; var instance = (IChangeTrackingObject)context.Instance;&nbsp; &nbsp; &nbsp; &nbsp; //The type name always prefixes the property&nbsp; &nbsp; &nbsp; &nbsp; var propertyName = context.PropertyName.Split(new[] { '.' }, 2).Skip(1).First();&nbsp; &nbsp; &nbsp; &nbsp; if (false == instance.GetChangedProperties().ContainsKey(propertyName))&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; var oldValue = instance.GetChangedProperties().Get(propertyName).OldValue;&nbsp; &nbsp; &nbsp; &nbsp; var newValue = context.PropertyValue;&nbsp; &nbsp; &nbsp; &nbsp; if (oldValue == null && newValue == null)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if ((oldValue != null && oldValue.Equals(newValue)) ||&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;(newValue != null && newValue.Equals(oldValue)))&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return predicate(t, p, context);&nbsp; &nbsp; };}
打开App,查看更多内容
随时随地看视频慕课网APP