1

假設我有具有屬性typeid和薪水的實體Person。我建立這樣的兩個屬性業務規則:如何獲得自定義驗證錯誤?

public static partial class MyRules 
    { 
     public static ValidationResult Rule1(Person p, ValidationContext context) 
     {   

      if ((p.typeid == 1) && ((p.salary == null)) 
      { 
       return new ValidationResult("type 1 must should have salary", 
              new string[] { "Salary" }); 
      } 

      return ValidationResult.Success; 
     } 
    } 

的代碼放在與在服務器share.cs側。

所以當規則被違反時,我會有SubmitOperation.HasError = true;這種錯誤只有在調用SubmitChanges之後。並且錯誤不會在ValidationSummary中顯示

所以當SubmitOperation.HasError = true;我怎麼知道SubmitOperation錯誤是驗證錯誤而不是其他錯誤?當我可以將此錯誤標識爲驗證錯誤時,如何獲得驗證錯誤消息「類型1必須應該有薪水」並將其顯示給用戶?

回答

1

我知道這已經快一歲了,儘管如此,沒有人回答它。我還沒有回答任何問題,但我知道答案,(或至少1個可能的答案)(請(和謝謝)標記爲答案)。這是我在完成提交操作時處理驗證結果的方式。當調用SubmitChanges時,您需要使用回調和用戶狀態來調用重載。這可能有點令人困惑,因爲在回調函數(InsertEntityCompleted)中,我調用op.userstate回調函數,但是在這種情況下用戶狀態是如何使用的。

private void InsertEntityCompleted(SubmitOperation op) 
    { 
     var callback = op.UserState as Action<Exception, ICollection<ValidationResult>>; 
     if (callback != null) 
     { 
      var validationResults = new Collection<ValidationResult>(); 
      if (op.HasError) 
      { 
       foreach (var entity in op.EntitiesInError) 
       { 
        //HOW YOU KNOW SUBMIT OPERATION ERROR IS VALIDATION ERROR 
        if (entity.HasValidationErrors) 
         foreach (var validationResult in entity.ValidationErrors) 
         { 
          //HOW YOU WOULD GET THE ERROR MESSAGES AND MEMBER NAMES 
          var name = validationResult.MemberNames; 
          var error = validationResult.ErrorMessage; 
          validationResults.Add(validationResult); 
         } 

       } 
       op.MarkErrorAsHandled(); 
      } 
      //HOW YOU IDENTIFY ERROR AS VALIDATION ERROR AND NOT OTHER TYPE OF ERROR 
      if (op.Error != null && 
       op.Error is DomainOperationException && 
       (op.Error as DomainOperationException).Status == OperationErrorStatus.ValidationFailed) 
       //I CALLBACK NULL FOR EXCEPTIONS, BUT I KEEP THE VALIDATION RESULTS ON VALIDATION ERRORS 
       //THEN TO SHOW IT TO THE USER I IMPLEMENT INotifyDataErrorInfo IN MY VIEWMODEL 
       //AND MANAGE THE ERRORS THROUGH THAT IMPLEMENTATION, THE BOUND CONTROL SHOULD HAVE 
       //NotifyOnValidationError=True DEFINED IN THE BINDING 
       callback(null, validationResults); 
      else 
       callback(op.Error, validationResults); 
      _entityContext.Enitities.EntityContainer.Clear(); 
     } 
    }