【问题标题】:Why is my DataAnnotations-based manual validation not working?为什么我的基于 DataAnnotations 的手动验证不起作用?
【发布时间】:2013-01-22 13:40:14
【问题描述】:

我正在尝试使用 DataAnnotations 手动验证类。该应用程序是一个控制台应用程序,因此不涉及 MVC。我正在使用 .NET 4.0。

我从this article 获得了指导:唯一的区别似乎是我正在尝试使用元数据类。但我读过的其他内容表明这是可以做到的。

但是,在运行时,对象会通过验证。我在 MVC3 中使用过 DataAnnotations,并认为我对它们很好,但我很困惑。

我错过了什么?是否需要 System.ComponentModel.DataAnnotations 以外的程序集?

/// This is a partial-class addition to an Entity Framework class, so the properties are
/// defined in the EF .designer.cs file.  
[MetadataType(typeof(EntityMetadata.tblThingMetaData ))]
public partial class tblThing
{

}

元数据类:

public partial class tblThingMetaData
{
    [Required(AllowEmptyStrings = false, ErrorMessage = "Sequence number is required")]
    [RegularExpression("A")]
    public string seq_num { get; set; }
}

测试:

    [TestMethod]
    public void VerifyValidationWorksOnEntities()
    {
        tblThing newThing = new tblThing()
        {
            seq_num = "B"
        };

        List<ValidationResult> results = new List<ValidationResult>();
        bool validationResult = Validator.TryValidateObject(
            newThing,
            new ValidationContext(newThing, null, null),
            results,
            true);

        Assert.AreNotEqual(0, results.Count);
        Assert.IsFalse(validationResult);
    }

我尝试了其他变体:newThing.seq_num 为 null,仅验证 seq_num 属性等。它始终通过验证并且没有验证结果。测试总是失败。

非常感谢您给我的任何建议。

【问题讨论】:

    标签: validation .net-4.0 data-annotations


    【解决方案1】:

    找到答案here。显然,除非您在验证之前添加以下内容,否则这在 Silverlight 或 MVC 之外不起作用:

    TypeDescriptor.AddProviderTransparent(
       new AssociatedMetadataTypeTypeDescriptionProvider(
           typeof(tblThing),
           typeof(EntityMetadata.tblThingMetaData)
       ), typeof(tblThing));
    

    注意最后一个参数必须是typeof(tblThing),而不是newThing。即使有一个重载需要您与元数据关联的类型的单个实例,即使这是您计划验证的同一个实例,如果您提供实例而不是类型,它也将不起作用。

    很累,但至少现在可以了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-23
      相关资源
      最近更新 更多