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 必须有薪水”并将其显示给用户?

4

1 回答 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();
        }
    }
于 2011-08-16T18:40:43.987 回答