实体框架和数据注释,错误不显示

本文关键字:错误 显示 注释 框架 数据 实体 | 更新日期: 2023-09-27 18:04:24

我正在使用实体框架并尝试使用数据注释进行验证。我在谷歌上查了几个例子,发现到处都是相同的结构。我照着做了,但由于某种原因,我的错误没有在表格中显示出来。我知道,我可能必须用Validator类手动验证属性,但我不知道在哪里做。我知道我可以监听PropertyChanging事件,但它只传递属性的名称,而不是将要分配的值。有人知道我该怎么解决这个问题吗?

提前感谢。

[MetadataType(typeof(Employee.MetaData))]
public partial class Employee
{
    private sealed class MetaData
    {
        [Required(ErrorMessage = "A name must be defined for the employee.")]
        [StringLength(50, ErrorMessage="The name must  be less than 50 characters long.")]
        public string Name { get; set; }
        [Required(ErrorMessage="A username must be defined for the employee.")]
        [StringLength(20, MinimumLength=3, ErrorMessage="The username must be between 3-20 characters long.")]
        public string Username { get; set; }
        [Required(ErrorMessage = "A password must be defined for the employee.")]
        [StringLength(20, MinimumLength = 3, ErrorMessage = "The password must be between 3-20 characters long.")]
        public string Password { get; set; }
    }
}
在xaml

<fx:TextBox Width="250" Height="20" CornerRadius="5" BorderThickness="0" MaxLength="50" Text="{Binding Name, UpdateSourceTrigger=PropertyChanged, ValidatesOnExceptions=True, NotifyOnValidationError=True}" />
<fx:TextBox Width="250" Height="20" CornerRadius="5" BorderThickness="0" MaxLength="20" Text="{Binding Username, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True, NotifyOnValidationError=True}" />
<fx:PasswordBox Width="250" Height="20" CornerRadius="5" BorderThickness="0" MaxLength="20" Password="{Binding Password, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, ValidatesOnExceptions=True, NotifyOnValidationError=True}" />

编辑:(根据Rachel的注释实现IDataErrorInfo类)

public static class EntityHelper
{
    public static string ValidateProperty(object instance, string propertyName)
    {
        PropertyInfo property = instance.GetType().GetProperty(propertyName);
        object value = property.GetValue(instance, null);
        List<string> errors = (from v in property.GetCustomAttributes(true).OfType<ValidationAttribute>() where !v.IsValid(value) select v.ErrorMessage).ToList();
        return (errors.Count > 0) ? String.Join("'r'n", errors) : null;
    }
}
[MetadataType(typeof(Employee.MetaData))]
public partial class Employee:IDataErrorInfo
{
    private sealed class MetaData
    {
        [Required(ErrorMessage = "A name must be defined for the employee.")]
        [StringLength(50, ErrorMessage="The name must  be less than 50 characters long.")]
        public string Name { get; set; }
        [Required(ErrorMessage="A username must be defined for the employee.")]
        [StringLength(20, MinimumLength=3, ErrorMessage="The username must be between 3-20 characters long.")]
        public string Username { get; set; }
        [Required(ErrorMessage = "A password must be defined for the employee.")]
        [StringLength(20, MinimumLength = 3, ErrorMessage = "The password must be between 3-20 characters long.")]
        public string Password { get; set; }
    }
    public string Error { get { return String.Empty; } }
    public string this[string property]
    {
        get { return EntityHelper.ValidateProperty(this, property); }
    }
在xaml

<fx:TextBox Width="250" Height="20" CornerRadius="5" BorderThickness="0" MaxLength="50" Text="{Binding Name, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" />

实体框架和数据注释,错误不显示

我已经成功地实现了类似的场景,我强烈建议您看看它是如何在http://waf.codeplex.com/中实现的。它使用实体框架和WPF的数据注释验证。

使用实体框架进行此工作时可能遇到的一个重要问题是,数据注释验证器将忽略您的元数据,直到您在验证之前在代码中添加EntityObject的元数据:

TypeDescriptor.AddProviderTransparent(new 
    AssociatedMetadataTypeTypeDescriptionProvider(typeof(EntityObject)), 
    typeof(EntityObject));

附加信息:.NET 4使用Validator

时忽略RTM MetadataType属性

另外,我认为你的元数据应该是公开的,而不是密封的。

下面是dataerrorinfosupport的一段摘录,供快速参考:

    /// <summary>
    /// Gets an error message indicating what is wrong with this object.
    /// </summary>
    /// <returns>An error message indicating what is wrong with this object. The default is an empty string ("").</returns>
    public string Error { get { return this[""]; } }
    /// <summary>
    /// Gets the error message for the property with the given name.
    /// </summary>
    /// <param name="memberName">The name of the property whose error message to get.</param>
    /// <returns>The error message for the property. The default is an empty string ("").</returns>
    public string this[string memberName]
    {
        get
        {
            List<ValidationResult> validationResults = new List<ValidationResult>();
            if (string.IsNullOrEmpty(memberName))
            {
                Validator.TryValidateObject(instance, new ValidationContext(instance, null, null), validationResults, true);
            }
            else
            {
                PropertyDescriptor property = TypeDescriptor.GetProperties(instance)[memberName];
                if (property == null)
                {
                    throw new ArgumentException(string.Format(CultureInfo.CurrentCulture,
                        "The specified member {0} was not found on the instance {1}", memberName, instance.GetType()));
                }
                Validator.TryValidateProperty(property.GetValue(instance),
                    new ValidationContext(instance, null, null) { MemberName = memberName }, validationResults);
            }
            StringBuilder errorBuilder = new StringBuilder();
            foreach (ValidationResult validationResult in validationResults)
            {
                errorBuilder.AppendInNewLine(validationResult.ErrorMessage);
            }
            return errorBuilder.ToString();
        }
    }