I\'m using the MetaDataType Attribute on my domain model class. It it supposed to move the attribute information from the referenced class into the class that the MetadataTy
I'm in a similar situation, where the database existed before the coding began. So DB first seemed the natural choice. Generated classes, none of which have annotations. So added MetadataType, and found this stackOverflow page - and so tried ModelMetadataType. I tried it against a class, as well as an interface.
I tried using var validationContext = new ValidationContext(model);
instead of var editContext = new EditContext(model);
and got further when I used var result = Validator.TryValidateObject(model, validationContext, xxxxx, validateAllProperties: true);
I thought I figured it out when I tried editContext.AddDataAnnotationsValidation();
Although this works for a class with annotations, it doesn't work (for me) for partial classes using either [MetadataType] or [ModelMetadataType] attributes.
The only work-around I've found to work (for me) is to create a new class that wraps the model you're wanting to annotate. That means same properties but getters and setters pointing at original model. But at least the annotations will work!
public class Model
{
public int ID { get; set; }
public string Name { get; set; }
}
public class AnnotatedModel
{
private readonly Model model;
public AnnotatedModel(Model model)
{
this.model = model;
}
[Range(1, int.MaxValue)]
public int ID { get => model.ID; set => model.ID = value; }
[Required]
[StringLength(maximumLength: 10, ErrorMessage = "Name can't be longer than 10 characters.")]
public string Name { get => model.Name; set => model.Name = value; }
}
So to use the above, I needed to write this:
var model = new Model();
var annotatedModel = new AnnotatedModel(model);
var editContext = new EditContext(annotatedModel);
editContext.AddDataAnnotationsValidation();
var result = editContext.Validate();
If anyone can tell me what I'm missing, great! Otherwise I hope this work-around will be useful for somebody.