Reputation: 13975
I am attempting to perform manual validation of a class using DataAnnotations. The application is a console app, so MVC is not involved. I am using .NET 4.0.
I got my guidance from this article: the only difference appears to be that I am attempting to use a metadata class. But other things I've read suggest that this can be done.
But, at run time, the object passes validation. I've used DataAnnotations in MVC3 and thought I was pretty good with them, but I'm baffled.
What am I missing? Is there an assembly other than System.ComponentModel.DataAnnotations that's required?
/// 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
{
}
The metadata class:
public partial class tblThingMetaData
{
[Required(AllowEmptyStrings = false, ErrorMessage = "Sequence number is required")]
[RegularExpression("A")]
public string seq_num { get; set; }
}
The test:
[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);
}
I've tried other variations: newThing.seq_num
being null, validating the seq_num
property only, etc. It always passes validation and has no validation results. The test always fails.
Many thanks for any advice you can give me.
Upvotes: 2
Views: 505
Reputation: 13975
Found an answer here. Apparently, this doesn't work outside of Silverlight or MVC unless you add the following before validating:
TypeDescriptor.AddProviderTransparent(
new AssociatedMetadataTypeTypeDescriptionProvider(
typeof(tblThing),
typeof(EntityMetadata.tblThingMetaData)
), typeof(tblThing));
Note that the last parameter needs to be typeof(tblThing)
, not newThing
. Even though there's an overload that takes a single instance of the type you're associating with the metadata, and even if that's the same instance you plan to validate, it won't work if you provide an instance rather than a Type.
Tiresome, but at least it works now.
Upvotes: 3