如何获得自定义验证错误?

时间:2010-10-21 16:31:15

标签: silverlight silverlight-4.0 wcf-ria-services domainservices

假设我有实体Person,其属性为typeid和salary。我为这两个属性构建了一个业务规则,如:

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 个答案:

答案 0 :(得分: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();
        }
    }