为了账号安全,请及时绑定邮箱和手机立即绑定

FluentValidations 从 RuleBuilderOptions 获取属性名

FluentValidations 从 RuleBuilderOptions 获取属性名

C#
HUWWW 2021-06-04 16:45:17
我正在尝试创建一个自定义 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从规则中获取?
查看完整描述

1 回答

?
牧羊人nacy

TA贡献1862条经验 获得超7个赞

我最终创建了一个 must 扩展,所以我可以访问属性验证器上下文:


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

    };

}


查看完整回答
反对 回复 2021-06-05
  • 1 回答
  • 0 关注
  • 158 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信