views:

232

answers:

2

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.

A: 

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.

eduncan911
A: 

Answer

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

jcruz