4

我对MSDN 示例有点困惑。

目前尚不清楚如何处理和设置实体相关的错误。

示例中的代码:

public System.Collections.IEnumerable GetErrors(string propertyName)
{
    if (String.IsNullOrEmpty(propertyName) || 
        !errors.ContainsKey(propertyName)) return null;
    return errors[propertyName];
}

但 GetErrors() 的文档指出:

propertyName - 要检索验证错误的属性的名称;或 null 或 Empty,以检索实体级错误

另一个例子建议只返回字典的 _errors.Values 。这只是所有属性错误,但又不是实体错误。

4

2 回答 2

2

As per the "Remarks" section from the documentation: MSDN: INotifyDataErrorInfo Interface

This interface enables data entity classes to implement custom validation rules and expose validation results asynchronously. This interface also supports custom error objects, multiple errors per property, cross-property errors, and entity-level errors. Cross-property errors are errors that affect multiple properties. You can associate these errors with one or all of the affected properties, or you can treat them as entity-level errors. Entity-level errors are errors that either affect multiple properties or affect the entire entity without affecting a particular property.

I might suggest that the implementation of GetErrors is highly dependent upon your error handling scheme. If, for instance, you do not intend to support Entity-Level errors, then your example code is sufficient. If, however, you do need to support Entity-Level errors, then you may handle the IsNullOrEmpty condition separately:

Public IEnumerable GetErrors(String propertyName)
{
    if (String.IsNullOrEmpty(propertyName))
        return entity_errors;
    if (!property_errors.ContainsKey(propertyName))
        return null;
    return property_errors[propertyName];
}
于 2013-06-18T07:17:40.310 回答
1

由于我的解决方案在这里没有找到正确的答案,因此当值为 null 或为空时,将返回所有验证错误:

private ConcurrentDictionary<string, List<ValidationResult>> modelErrors = new ConcurrentDictionary<string, List<ValidationResult>>();

public bool HasErrors { get => modelErrors.Any(); }

public IEnumerable GetErrors(string propertyName)
{
    if (string.IsNullOrEmpty(propertyName))
    {
        return modelErrors.Values.SelectMany(x => x);   // return all errors
    }
    modelErrors.TryGetValue(propertyName, out var propertyErrors);
    return propertyErrors;
}
于 2019-02-03T14:25:50.830 回答