gpt4 book ai didi

validation - 为什么我的基于 DataAnnotations 的手动验证不起作用?

转载 作者:行者123 更新时间:2023-12-04 05:14:31 31 4
gpt4 key购买 nike

我正在尝试使用 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为空,验证 seq_num property only 等。它总是通过验证并且没有验证结果。测试总是失败。

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

最佳答案

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

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

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

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

关于validation - 为什么我的基于 DataAnnotations 的手动验证不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14459925/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com