I have a model with an Entity Framework object on it. The EF object implements IValidatableObject
and has a Validate() method on it.
For some reason the method runs twice, so I get two identical model errors on my page.
Any idea why this happens or how to stop it?
I tried adding an _isValidated
private member variable but it appears to be resetting to false every time it runs so it must be creating and validating two instances of the model.
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (string.IsNullOrWhiteSpace(CatName))
{
yield return new ValidationResult("Bad kitty", new string[] { "CatName", "CatName" });
}
}
Edit: My model:
public class KittyModel
{
public Cat Cat { get; set; }
public int? SomeId { get; set; }
public string SomeString { get; set; }
}
Then Cat
is just an EF object
[MetadataType(typeof(CatMetadata))]
public partial class Cat : IValidatableObject
{
public sealed class CatMetadata
{
[Required]
public int? CatTypeID { get; set; }
}
// Some other get; only properties here
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (string.IsNullOrWhiteSpace(CatName))
{
yield return new ValidationResult("Bad kitty", new string[] { "CatName", "CatName" });
}
}
}