如何使用 MetaData 类验证数据注释
我正在尝试使用数据注释但使用元数据类来验证类。
[MetadataType(typeof(TestMetaData))]
public class Test
{
public string Prop { get; set; }
internal class TestMetaData
{
[Required]
public string Prop { get; set; }
}
}
[Test]
[ExpectedException(typeof(ValidationException))]
public void TestIt()
{
var invalidObject = new Test();
var context = new ValidationContext(invalidObject, null, null);
context.MemberName = "Prop";
Validator.ValidateProperty(invalidObject.Prop, context);
}
测试失败。如果我放弃元数据类并只装饰实际类上的属性,它就可以正常工作。我做错了什么?这让我处于疯狂的边缘。请帮忙。
I'm trying to validate a class using Data Annotations but with a metadata class.
[MetadataType(typeof(TestMetaData))]
public class Test
{
public string Prop { get; set; }
internal class TestMetaData
{
[Required]
public string Prop { get; set; }
}
}
[Test]
[ExpectedException(typeof(ValidationException))]
public void TestIt()
{
var invalidObject = new Test();
var context = new ValidationContext(invalidObject, null, null);
context.MemberName = "Prop";
Validator.ValidateProperty(invalidObject.Prop, context);
}
The test fails. If I ditch the metadata class and just decorated the property on the actual class it works fine. WTH am I doing wrong? This is putting me on the verge of insanity. Please help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
答案
这是一个链接帮助我解决这个问题的帖子。显然你必须先注册 matadata 类。
Answer
Here is a link to the post that helped me solve this issue. Apparently you have to register the matadata class first.
元数据类必须是公共的,外部验证才能正常工作。
我相信在模型类中定义元数据类(就像您在示例中所做的那样)应该可行。还没有测试过。
The metadata class must be public for the external validation to work.
I believe defining the metadata class inside of your model class, like you did in your example, should work. Haven't tested it.