【发布时间】: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