开发者

How to validate Data Annotations with a MetaData class

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
    {
        [Requir开发者_StackOverflowed]
        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.


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.

[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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜