亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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 關注
  • 199 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號