如何使用 MetaData 类验证数据注释

发布于 2024-08-18 22:55:08 字数 603 浏览 4 评论 0原文

我正在尝试使用数据注释但使用元数据类来验证类。

[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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

与他有关 2024-08-25 22:55:08

答案

这是一个链接帮助我解决这个问题的帖子。显然你必须先注册 matadata 类。

Answer

Here is a link to the post that helped me solve this issue. Apparently you have to register the matadata class first.

葬心 2024-08-25 22:55:08

元数据类必须是公共的,外部验证才能正常工作。

[MetadataType(typeof(TestMetaData))] 
public class Test 
{ 
    public string Prop { get; set; } 

    public class TestMetaData 
    { 
        [Required] 
        public string Prop { get; set; } 
    } 
}

我相信在模型类中定义元数据类(就像您在示例中所做的那样)应该可行。还没有测试过。

The metadata class must be public for the external validation to work.

[MetadataType(typeof(TestMetaData))] 
public class Test 
{ 
    public string Prop { get; set; } 

    public class TestMetaData 
    { 
        [Required] 
        public string Prop { get; set; } 
    } 
}

I believe defining the metadata class inside of your model class, like you did in your example, should work. Haven't tested it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文